python的print输出txt

方法一:

import sys
newfile = 'C:\VisualSTUDIO\climbdouban\soup.txt'
data = open(newfile,'w',encoding="utf-8")
sys.stdout = data
……
data.close()

方法二(推荐):

print(content,file=file12345)

python中将print输出为txt碰到问题的时候
碰到报错UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\xa0’ in position 9259: illegal multibyte sequence
将保存的txt文件加个编码

data = open(newfile,'w')

改为

data = open(newfile,'w',encoding="utf-8")

猜你喜欢

转载自blog.csdn.net/weixin_43970884/article/details/89496435