Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a Line Break to a User Input Variable Python Then Storing it in a JSON File

So I have this program and in the program is a Tkinter entry box and when the user clicks the submit button it stores the input to a JSON file. How can I add a line break after the string has been written in JSON file?

I’ve tried using the newline="\r\n" in the

with open(udf, "a", newline="\r\n") as file_object:
    json.dump(usern, file_object)

By the way, the varible usern is what the user typed in to the entry box.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And the new line feature in it:

with open(udf, "a") as file_object:
    json.dump(usern + "\n", file_object)

But none of it worked

>Solution :

The json module does not support adding newlines to the file when dumping data.

You can use file_object.write("\n") to add it to the file after dumping:

with open(udf, "a") as file_object:
    json.dump(usern, file_object)
    file_object.write("\n")

Or convert it to a string with json.dumps() and make a single write operation:

with open(udf, "a") as file_object:
    json_string = json.dumps(usern) + "\n"
    file_object.write(json_string)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading