使用 python 编解码器保存文件

Saving files with python codecs

我有两个代码示例,它们应该执行相同的操作(处理文本文件并将结果保存到输出文件)。 但是,这个对我不起作用:

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')))

...打开文件对象而不传递任何文本。您需要添加 read() 才能使其正常工作,如下所示:codecs.open(f, 'r', 'utf-8').read()