如何在Python中将文件转换为utf-8?
我需要在Python中将一堆文件转换为utf-8,并且在“转换文件”部分遇到问题。
我想做相当于:
iconv -t utf-8 $file > converted/$file # this is shell code
谢谢!
您可以使用编解码器模块 ,如下所示:
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
参数来控制文件块的大小。
这在一个小testing中为我工作:
sourceEncoding = "iso-8859-1" targetEncoding = "utf-8" source = open("source") target = open("target", "w") target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))
感谢答复,它的作品!
而且,由于源文件是混合格式,我添加了一个按顺序尝试的源格式列表( 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的替代方法)
这是一个用于将任何文本文件转换为UTF-8编码的Python3函数。 (不使用不必要的软件包)
def correctSubtitleEncoding(filename, newFilename, encoding_from, encoding_to='UTF-8'): with open(filename, 'r', encoding=encoding_from) as fr: with open(newFilename, 'w', encoding=encoding_to) as fw: for line in fr: fw.write(line[:-1]+'\r\n')
您可以在循环中轻松使用它来转换文件列表。
要猜测什么是源编码,可以使用file
* nix命令。
例:
$ file --mime jumper.xml jumper.xml: application/xml; charset=utf-8