[英]How to Print To Text File?
I want print my output to text file. 我想将输出打印到文本文件。 Jow can I fix my code? 我可以修复我的代码吗?
for h3 in parse.find_all('h3', {'class': "_1hETr2dodrTLejwpCPNjNp"}):
account = '{}:{}:{}'.format(ab_form, ft_form, h3.get_text())
print(account)
output = open("./output.txt", "r")
output.write(account)
You need a +
in your file open to create the file if it does not exist. 如果文件不存在,则需要在文件中打开+
。
Also, there is little value opening the file each time through the loop. 同样,每次通过循环打开文件的价值很小。
with open("./output.txt", "a+") as fd:
for h3 in parse.find_all('h3', {'class': "_1hETr2dodrTLejwpCPNjNp"}):
account = '{}:{}:{}\n'.format(ab_form, ft_form, h3.get_text())
fd.write(account)
I will assume that the rest of the script does what you need it to do. 我将假定脚本的其余部分完成了您需要执行的操作。
for h3 in parse.find_all('h3', {'class': "_1hETr2dodrTLejwpCPNjNp"}):
account = '{}:{}:{}\n'.format(ab_form, ft_form, h3.get_text())
with open("./output.txt", "a") as fd:
fd.write(account)
note \\n newline separator and 'a' append mode as you are doing multiple writes 注意\\ n换行分隔符和'a'附加模式,因为您要进行多次写入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.