如何在Python中将文件转换为utf-8?

83 投票
10 回答
178999 浏览
提问于 2025-04-11 09:26

我需要在Python中把一堆文件转换成utf-8格式,但在“转换文件”这部分遇到了麻烦。

我想做的事情类似于:

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

谢谢!

10 个回答

17

谢谢大家的回复,问题解决了!

因为源文件的格式不一样,我添加了一个要尝试的格式列表(sourceFormats),当遇到UnicodeDecodeError错误时,我就尝试下一个格式:

from __future__ import with_statement

import os
import sys
import codecs
from chardet.universaldetector import UniversalDetector

targetFormat = 'utf-8'
outputDir = 'converted'
detector = UniversalDetector()

def get_encoding_type(current_file):
    detector.reset()
    for line in file(current_file):
        detector.feed(line)
        if detector.done: break
    detector.close()
    return detector.result['encoding']

def convertFileBestGuess(filename):
   sourceFormats = ['ascii', 'iso-8859-1']
   for format in sourceFormats:
     try:
        with codecs.open(fileName, 'rU', format) as sourceFile:
            writeConversion(sourceFile)
            print('Done.')
            return
      except UnicodeDecodeError:
        pass

def convertFileWithDetection(fileName):
    print("Converting '" + fileName + "'...")
    format=get_encoding_type(fileName)
    try:
        with codecs.open(fileName, 'rU', format) as sourceFile:
            writeConversion(sourceFile)
            print('Done.')
            return
    except UnicodeDecodeError:
        pass

    print("Error: failed to convert '" + fileName + "'.")


def writeConversion(file):
    with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
        for line in file:
            targetFile.write(line)

# Off topic: get the file list and call convertFile on each file
# ...

(Rudro Badhon 编辑:这个方法结合了原来的多种格式尝试,直到没有异常出现的方式,以及一种使用 chardet.universaldetector 的替代方法)

35

这个在我做的小测试中有效:

sourceEncoding = "iso-8859-1"
targetEncoding = "utf-8"
source = open("source")
target = open("target", "w")

target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))
64

你可以使用 codecs模块,像这样:

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)

编辑: 添加了 BLOCKSIZE 参数来控制文件的块大小。

撰写回答