Storing Variable in a Python TXT File

Asked

Viewed 961 times

0

Greetings,I made that algorithm CODE BELOW:

from bs4 import BeautifulSoup
soup=BeautifulSoup(html,'html.parser')
for link in soup.select('div.sg-actions-list__hole > a[href*="/tarefa"]'):
    ref=link.get('href')
    rt = ('https://brainly.com.br'+str(ref))
    p.append(rt)
print(p)

for url in p:
    r = requests.get(url).text
    time.sleep(10)
    print(r) 

Basically Store the Url in a List and Then in a Loop Print the Source_code.

My Doubt and How to Transform the Variable r in an Archive TXT

  • with open('file', 'w') as f: f.write(r)

1 answer

1


Use the function open() passing as parameter the file name and the opening mode, which will be in this case "w" to carry out writing in this way:

file = open("arquivo.txt","w")

After that, save the information to the file using the method write() and finally, close the file with the method close() to save the changes. Your code would look like this:

file = open("arquivo.txt","w")
file.write(r)
file.close()
  • I advise to use with to open files to ensure the release of your resources. This answer details better on the subject

Browser other questions tagged

You are not signed in. Login or sign up in order to post.