如何在Python中将输出内容写入文件 [英] How to write output content to a file in Python
本文介绍了如何在Python中将输出内容写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以打印任何网站的内容但我无法将该内容写入文件。
在这里,我想将内容(即文本中的内容)写入a文件名为key.txt
请帮忙!这是我的项目!!
我尝试过:
I am able to print the content of any website but im not able to write that content to a file.
Here, i want to write the content(i.e., text in this) to a file named key.txt
Please help! This is for my project!!
What I have tried:
from urllib.request import urlopen
import re
from bs4 import BeautifulSoup
url = input("enter full url:")
pattern = re.compile("[\w]+.[\w]+")
matchobject = pattern.match(url)
if (matchobject):
print("your website is:",url)
html =urlopen(url).read().decode()
soup = BeautifulSoup(html,"html.parser")
for script in soup(["script", "style"]):
script.extract()
text = soup.get_text()
print(text)
with open("C:\\Users\\Aishwarya\\Desktop\\key.txt", "w") as text_file:
text_file.write(text) # i have doubt over here
text_file.close()
推荐答案
看看这里: Python for Beginners - 用Python读取和编写文件 [ ^ ]。
这篇关于如何在Python中将输出内容写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文