How to write a list to a text file in the correct format

Posted by lia1000 on Stack Overflow See other posts from Stack Overflow or by lia1000
Published on 2014-06-05T09:20:26Z Indexed on 2014/06/05 9:25 UTC
Read the original article Hit count: 125

Filed under:
|

I've got this piece of code that I want to write the output to a text file but with the correct format i.e. no brackets, single quotes so it appears as a formatted list.

This is the code:

file = open("env5.txt", "w");
for key in os.environ.keys():
  env = os.environ[key];
  key1 = key;
  list = str([key, env]).replace("'","").replace('[]', '');
  list2 = list[1:-1];
  print(list2);
  file.writelines(list2);

file.close();

This is the original code:

for key in os.environ.keys():
print(key, os.environ[key]);

Many thanks

© Stack Overflow or respective owner

Related posts about python

Related posts about python-3.x