0

I have some code that creates a dictionary and pastes it into a text file. But it pastes the dictionary as one line. Below I have the code and the textfile it creates.

print('Writing to Optimal_System.txt in %s\n' %(os.getcwd()))    
f = open('Optimal_System.txt','w')
f.write(str(optimal_system))
f.close  

Is there any way to make the textfile give each key-value pair it's own line like this?

{'Optimal Temperature (K)': 425
 'Optimal Pressure (kPa)': 100
 ...
}

enter image description here

bbalzano
  • 33
  • 5
  • 1
    As the duplicate target suggests, use the [json](https://docs.python.org/3/library/json.html) module to do this. – snakecharmerb Jan 06 '19 at 19:09
  • Iterate over the key,value pairs of `yourdictionary.items()`; use [string formatting](https://docs.python.org/3.7/library/string.html#format-string-syntax) to construct a line (with a newline character) from each key/value; write the line to the file. – wwii Jan 06 '19 at 19:25

3 Answers3

2

Using formatting string and assuming that optimal_system is your dictionary:

with open('output.txt', 'w') as f:
    for k in optimal_system.keys():
        f.write("{}: {}\n".format(k, optimal_system[k]))

EDIT

As pointed by @wwii, the code above can be also written as:

with open('output.txt', 'w') as f:
    for k, v in optimal_system.items():
        f.write("{}: {}\n".format(k, v))

And the string can be formatted using formatted string literals, available since python 3.6, hence f'{k}: {v}\n' instead of "{}: {}\n".format(k, v).

Valentino
  • 7,291
  • 6
  • 18
  • 34
  • 1
    `for k,v in optimal_system.items(): ... .format(k,v)...`. And for Python 3.6 the line can be made with an [f-string](https://docs.python.org/3.7/reference/lexical_analysis.html#f-strings) - `f'{k}: {v}\n`. – wwii Jan 06 '19 at 19:52
  • @wwii I will add this in the answer, thanks! – Valentino Jan 06 '19 at 20:12
  • Thank you, this works great. Just curious though, should I type in "f.close()" outside the for loop just to make sure its closed? – bbalzano Jan 06 '19 at 21:50
  • @bbalzano with the construct `with open('filename', 'w') as f:` calling `f.close()` is not needed. Have a look [here](https://stackoverflow.com/questions/49512990/does-python-gc-close-files-too) for more details. – Valentino Jan 06 '19 at 22:49
2

You can use the pprint module -- it also works for all other data structures. To force every entry on a new line, set the width argument to something low. The stream argument lets you directly write to the file.

import pprint
mydata = {'Optimal Temperature (K)': 425,
          'Optimal Pressure (kPa)': 100,
          'other stuff': [1, 2, ...]}
with open('output.txt', 'w') as f:
    pprint.pprint(mydata, stream=f, width=1)

will produce:

{'Optimal Pressure (kPa)': 100,
 'Optimal Temperature (K)': 425,
 'other stuff': [1,
                 2,
                 Ellipsis]}
user24343
  • 892
  • 10
  • 19
0

You can use json.dumps() to do this with the indent parameter. For example:

import json

dictionary_variable = {'employee_01': {'fname': 'John', 'lname': 'Doe'},
                       'employee_02': {'fname': 'Jane', 'lname': 'Doe'}}

with open('output.txt', 'w') as f:
    f.write(json.dumps(dictionary_variable, indent=4))
hamzaahmad
  • 133
  • 2
  • 7