2

My issue:

I need to out every item in a dictionary to an external text file in Python. Like the following:

dict1 = {}

gen1 = 1
aha = 2

dict1['Generation'] = gen1 
dict1['Population'] = aha

  for key, value in sorted(dict1.items()):
      print(key,':',value, file = open('text.txt', 'w'))

In this example I have 2 keys in the dictionary however when I run the code and go to the file the only line which has been made only the first key is outputted.

What Can I do so that all of the keys in the dictionary are printed in the external file?

thank you

3 Answers3

1

You should use json module to dump your dict into a file, instead of reinventing the wheel:

import json

dict1 = {}

gen1 = 1
aha = 2

dict1['Generation'] = gen1 
dict1['Population'] = aha

with open('text.txt', 'w') as dict_file:
    json.dump(dict1, dict_file)
mvelay
  • 1,520
  • 1
  • 10
  • 23
1

Every call to open('text.txt', 'w') will truncate the file. That means, before writing the second item, the file will be cleared and the first item is lost.

You should only open it once and keep it in a variable:

# not final solution yet!
f = open('text.txt', 'w')
for key, value in sorted(dict1.items()):
    print(key, ':', value, file=f)

However in Python, most of the time you should use the with statement to ensure the file is properly closed:

with open('text.txt', 'w') as f:
    for key, value in sorted(dict1.items()):
        print(key, ':', value, file=f)
Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
1

You are re-opening the file for writing (and thus clearing it) in each iteration of your for loop. Use

with open('text.txt', 'w') as out:
   for key, value in sorted(dict1.items()):
       print(key,':',value, file=out)

Alternatively, simply change open('text.txt', 'w') to open('text.txt', 'a') in your original code in order to open the file for appending. This is less efficient than only opening the file once, though.

timgeb
  • 76,762
  • 20
  • 123
  • 145