首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Python中将文件转换为utf-8?

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

Stack Overflow用户
提问于 2008-10-10 21:50:26
回答 9查看 129.4K关注 0票数 67

我需要在Python中将一堆文件转换为utf-8,并且我在“转换文件”部分遇到了问题。

我想做的等同于:

代码语言:javascript
运行
复制
iconv -t utf-8 $file > converted/$file # this is shell code

谢谢!

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2008-10-10 13:59:08

您可以像这样使用codecs module

代码语言:javascript
运行
复制
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参数来控制文件块大小。

票数 56
EN

Stack Overflow用户

发布于 2008-10-10 14:07:08

在一个小测试中,这对我很有效:

代码语言:javascript
运行
复制
sourceEncoding = "iso-8859-1"
targetEncoding = "utf-8"
source = open("source")
target = open("target", "w")

target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))
票数 34
EN

Stack Overflow用户

发布于 2008-10-10 16:14:46

谢谢你的回复,它起作用了!

由于源文件采用混合格式,因此我添加了一个按顺序尝试的源格式列表(sourceFormats),并在UnicodeDecodeError上尝试下一种格式:

代码语言:javascript
运行
复制
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的替代方法)

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/191359

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档