使用 python 编解码器保存文件

弗雷莫里

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

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 编解码器上做错了什么吗?谢谢!

cs95

这条线...

outfile.write(some_function(codecs.open(f, 'r', 'utf-8')))

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Linux上的python中使用mbcs编解码器读取csv文件?

致命的Python错误:initfsencoding:无法加载文件系统编解码器

使用Quarkus在MongoDb中注册编解码器

使用编解码器,unicode_escape()进行Python编码和解码

使用MediaRecorder指定编解码器

Python'ascii'编解码器无法使用request.get编码字符

自定义Python Charmap编解码器

Bioformats-Python错误:使用OMEXML()时,“ ascii”编解码器无法编码字符u'\ xb5'

Python使用euc-kr编码以意外方式对(韩语)字符进行编码(编解码器,编码模块)

致命的python错误的原因可能是什么:initfsencoding:无法加载文件系统编解码器?

Sqoop:使用Gzip编解码器的Avro失败

使用JSON载入在Python 3.6中产生“ ascii编解码器无法编码字符”错误

使用UTF-8字符串写入文件时发生Python编解码器错误

使用Python C扩展时如何解决“ UnicodeDecodeError:'utf-8'编解码器无法解码字节”的问题?

使用Webengine视频和音频编解码器

UnicodeDecodeError'utf-8'编解码器无法解码-使用python shapefile阅读器

Python-下载的视频文件出现编解码器问题

致命的Python错误:Py_Initialize:无法加载文件系统编解码器和ModuleNotFoundError

使用pyarrow的Python错误-ArrowNotImplementedError:未构建对编解码器'snappy'的支持

如何找到未使用特定编解码器编码的媒体文件?

在Python中使用编解码器编码的正确方法是什么?

尝试写入使用编解码器lib打开的文件时出现ascii错误

如何使用Opus编解码器编码音频?

在Python3中为print()使用编解码器错误处理程序?

如何使用libvlc检索编解码器信息?

为什么 Linux 使用非自由编解码器,为什么需要编解码器?

使用 Python 编解码器但仍然收到 UnicodeDecodeError

Python TypeError:使用“cp1252”编解码器编码失败

python 3 - UnicodeEncodeError: 'charmap' 编解码器无法编码字符(编码所以它在文件中)