如何用python将中文文本写入文件

2024-05-16 05:28:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在提取中文文本并将其写入文件时遇到问题。在

str = "全球紧张致富豪财富缩水 贝索斯丁磊分列跌幅前两位";
f=open('test.txt','w');
f.write(str);

上面的代码运行良好。在写文件时,下面的代码显示出胡言乱语。在

^{pr2}$

谢谢你的帮助


Tags: 文件代码test文本txtopen全球write
2条回答

解决。。在

刚刚将.text更改为.content

plain_text = source_code.text to plain_text = source_code.content

以获得中文文本的输出。在

得到了预期的结果

在python2中,使用编解码器.打开()如果您处理的是ASCII以外的编码。你不需要手动编码。也,手术室步行如果文件名中需要非ASCII字符,则应向()传递Unicode字符串:

import codecs
with codecs.open("c:/Users/me/filename.txt", "a", encoding="utf-8") as d:
   for dir, subdirs, files in os.walk(u"c:/temp"):
      for f in files:
         fname = os.path.join(dir, f)
         print fname
         d.write(fname + "\n")

不需要调用d.close(),with块已经处理好了。在

相关问题 更多 >