4

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.

Tek Nath
  • 1,374
  • 1
  • 18
  • 34
grag1337
  • 91
  • 1
  • 6

2 Answers2

5

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)
i_am_deesh
  • 369
  • 2
  • 10
4

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()
U12-Forward
  • 65,118
  • 12
  • 70
  • 89