简体   繁体   中英

How to write a list to a new line in a file for Python

import json
f = open("Troubleshooting.txt","a")
json.dump(problem,f)
f.close()

I've tried using json but it keeps writing the list on a single line which makes it extremely messy. For example - json.dump(problem) Writes in the txt file: ["Phone has gotten wet", "The display is broken", "The phone does not charge", "There is no sound", "The interface is slow", "Nothing is saving"]

Then when the script is restarted with different values: json.dump(problem) Simply adds on this to the previous list: ["The phone doesn't turn on", "The phone does not charge"]

Making it all together be one line saying: ["Phone has gotten wet", "The display is broken", "The phone does not charge", "There is no sound", "The interface is slow", "Nothing is saving"]["The phone doesn't turn on", "The phone does not charge"]

Is there any way to make the other parts be written on a new line?

You can use f.write('\\n') to add a new line to the file.

IE make your code into:

import json
f = open("Troubleshooting.txt","a")
f.write('\n')
json.dump(problem,f)
f.close()

You can manually add newlines, like so

f = open("Troubleshooting.txt","a")
f.write('\n')
json.dump(problem,f)
f.close()

But also you don't necessarily even need to use JSON, if you just want strings you could iterate over the list and write each as a new line.

f = open("Troubleshooting.txt","a")
for line in problem:
    f.write(line + '\n')
f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM