Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a multi line string to a text file using Python

I'm trying to write multiple lines of a string to a text file in Python3, but it only writes the single line.

e.g

Let's say printing my string returns this in the console;

>> print(mylongstring)
https://www.link1.com
https://www.link2.com
https://www.link3.com
https://www.link4.com
https://www.link5.com
https://www.link6.com

And i go to write that into a text file

f = open("temporary.txt","w+")
f.write(mylongstring)

All that reads in my text file is the first link (link1.com)

Any help? I can elaborate more if you want, it's my first post here after all.

like image 568
pseudoepinephrine Avatar asked May 13 '26 14:05

pseudoepinephrine


2 Answers

never open a file without closing it again at the end. if you don't want that opening and closing hustle use context manager with this will handle the opening and closing of the file.

x = """https://www.link1.com
https://www.link2.com
https://www.link3.com
https://www.link4.com
https://www.link5.com
https://www.link6.com"""

with open("text.txt","w+") as f:
    f.writelines(x)
like image 175
i_am_deesh Avatar answered May 16 '26 03:05

i_am_deesh


Try closing the file:

f = open("temporary.txt","w+")
f.write(mylongstring)
f.close()

If that doesn't work try using:

f = open("temporary.txt","w+")
f.writelines(mylongstring)
f.close()

If that still doesn't work use:

f = open("temporary.txt","w+")
f.writelines([i + '\n' for i in mylongstring])
f.close()
like image 33
U12-Forward Avatar answered May 16 '26 02:05

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!