当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在Python中将文件转换为utf-8?》经验,为你挑选了3个好方法。

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

我想做相当于:

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

谢谢!



1> DzinX..:

您可以使用编解码器模块,如下所示:

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参数来控制文件块大小.


read()将始终读取整个文件 - 您可能需要.read(BLOCKSIZE),其中BLOCKSIZE是一次适当的读/写量.
没错,谢谢。我将修改我的示例。

2> Staale..:

这在一个小测试中对我有用:

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

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



3> Sébastien Ro..:

谢谢你的回复,它的确有效!

由于源文件是混合格式,我添加了一个源序列列表,在sequence(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的替代方法)

推荐阅读
臭小子
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有