我有两个代码示例,它们应该执行相同的操作(处理文本文件并将结果保存到输出文件)。但是,这个对我不起作用:
with codecs.open('outfile.txt', 'w', 'utf-8') as outfile:
for f in os.listdir(my_files):
outfile.write(some_function(codecs.open(f, 'r', 'utf-8')))
outfile.write('\n')
而这完美地工作:
outfile = open('outfile.txt', 'w')
for f in os.listdir(my_files)
with open(f) as f_:
text = f_.read().decode('utf-8')
text = some_function(text)
outfile.write(text.encode('utf-8'))
outfile.write('\n')
我在 python 编解码器上做错了什么吗?谢谢!
这条线...
outfile.write(some_function(codecs.open(f, 'r', 'utf-8')))
...打开一个文件对象而不传递任何文本。您需要添加 aread()
以使其正常工作,如下所示:codecs.open(f, 'r', 'utf-8').read()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句