-1

I'm trying to make a GUI where a button writes a certain string of text into the 'link_list' txt file. When this line of text is written it stays on the same line. I want the line of text, printed from the button, to go to a separate line each time it is printed

f = open('link_list.txt', 'a+')
f.write("test ")
f.close()

(I repeated the function 5 times to better show what i meant

Output:

test test test test test 

Intended Output:

test
test
test
test
test
  • Does this answer your question? [How do I specify new lines on Python, when writing on files?](https://stackoverflow.com/questions/11497376/how-do-i-specify-new-lines-on-python-when-writing-on-files) – AMC Mar 07 '20 at 03:45
  • As an aside, I would recommend always using a context manager to handle file objects. – AMC Mar 07 '20 at 03:45

2 Answers2

2

There are a couple ways to do this. The easiest way is to write in a "\n" character when you want a "N"ew line. The slash means whatever is next- is a special character.

replace

f.write("test ")

with this

f.write("test\n")

But I would start using pathlib for all your file writing needs:

from pathlib import Path
f = Path('link_list.txt')
with f.open("a"):
    f.write_text("test\n")
Back2Basics
  • 7,406
  • 2
  • 32
  • 45
2

Try to add a line feed character:

f = open('link_list.txt', 'a+')
f.write("test\n")
f.close()

even better with a context manager:

with open('link_list.txt', 'a+') as f:
    f.write("test\n")

This will ensure that your file is correctly closed even if an error occurs during the write operation.

Frodon
  • 3,684
  • 1
  • 16
  • 33