7

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 Acharya
  • 1,676
  • 2
  • 20
  • 35
pseudoepinephrine
  • 121
  • 1
  • 1
  • 6

3 Answers3

10

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
i_am_deesh
  • 448
  • 3
  • 12
5

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()
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
-1

Try this

import pandas as pd

data = []  # made empty list

data.append(mylongstring)  # added all the str values to empty list data using append

df = pd.DataFrame(data, columns=['Values']) # creating dataframe

df_string = df.to_string(header=False, Index= False)
with open('output.txt', 'w+') as f:
    f.write(df_string)  # Saving the data to txt file
  • Pandas is overkill for this. And why bother setting a column label if you're not going to use it? – wjandrea Jun 29 '23 at 23:13
  • `TypeError: to_string() got an unexpected keyword argument 'Index'` The problem is `Index='False'` should be `index=False`. – wjandrea Jun 29 '23 at 23:15
  • This doesn't even work properly. It writes the string with escaped newlines. Maybe you meant `pd.DataFrame(mylongstring.split('\n'))`. But still, Pandas is overkill for this. – wjandrea Jun 29 '23 at 23:19
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 01 '23 at 14:25