Writing a dictionary to a textile line by line

185 Views Asked by At

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

3

There are 3 best solutions below

4
Valentino On BEST ANSWER

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).

0
hamzaahmad On

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))
0
user24343 On

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]}