pseudoepinephrine
pseudoepinephrine

Reputation: 141

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.

Upvotes: 9

Views: 25204

Answers (4)

Greendhii
Greendhii

Reputation: 1

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".

Upvotes: 0

Shubham Vashisht
Shubham Vashisht

Reputation: 3

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

Upvotes: -1

i_am_deesh
i_am_deesh

Reputation: 486

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)

Upvotes: 13

U13-Forward
U13-Forward

Reputation: 71560

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

Upvotes: 5

Related Questions