如何在 Python 中将文件转换为 utf-8? [英] How to convert a file to utf-8 in Python?

查看:91
本文介绍了如何在 Python 中将文件转换为 utf-8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Python 中将一堆文件转换为 utf-8,我在转换文件"部分遇到了麻烦.

I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.

我想做相当于:

iconv -t utf-8 $file > converted/$file # this is shell code

谢谢!

推荐答案

您可以使用 编解码器模块,像这样:

You can use the codecs module, like this:

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)

EDIT:添加了 BLOCKSIZE 参数来控制文件块大小.

EDIT: added BLOCKSIZE parameter to control file chunk size.

这篇关于如何在 Python 中将文件转换为 utf-8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆