9

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.

12
  • Does this answer your question? write multiple lines in a file in python Commented Jan 22, 2020 at 4:56
  • What does print(type(mylongstring)) result in? Commented Jan 22, 2020 at 4:57
  • 1
    Please share your longstring variable how does it look. Commented Jan 22, 2020 at 4:57
  • Please share print(repr(mylongstring)). Commented Jan 22, 2020 at 4:58
  • 3
    So it's a list of strings, not a "multiline string". Those two things are completely different. Please make sure your question is correct. Commented Jan 22, 2020 at 5:06

4 Answers 4

13

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)
Sign up to request clarification or add additional context in comments.

Comments

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()

1 Comment

Prints out the first string letter by letter
0

This is what solved it for me:

import requests
from bs4 import BeautifulSoup

url = 'LinkWebsite'
headers = {'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"}
site = requests.get(url, headers=headers)
soup = BeautifulSoup(site.content, 'html.parser')
with open("yourfolder\yourfile.txt", "w") as f:
    for a in soup.find_all('a',href=True, class_='Live'):
        link = a['href']
        f.write(link+"\n")
f.close()

Basically I had to "elevate" f.write(link+"\n") to the "for" leaving it at the same height as "var" which is also created with the text wrapping function, if you don't want a line break just remove the +"\n".

Comments

-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

4 Comments

Pandas is overkill for this. And why bother setting a column label if you're not going to use it?
TypeError: to_string() got an unexpected keyword argument 'Index' The problem is Index='False' should be index=False.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.