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

2025-03-20 08:47:00
admin
原创
24
摘要:问题描述:我需要在 Python 中将一堆文件转换为 utf-8,但在“转换文件”部分我遇到了麻烦。我想做相当于的事情:iconv -t utf-8 $file > converted/$file # this is shell code 谢谢!解决方案 1:您可以使用编解码器模块,如下所示:impor...

问题描述:

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

我想做相当于的事情:

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

谢谢!


解决方案 1:

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

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

解决方案 2:

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

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

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

解决方案 3:

谢谢大家的回复,它有效!

由于源文件是混合格式,我添加了要按顺序尝试的源格式列表(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 的替代方法)

解决方案 4:

未知源编码类型的答案

基于@Sébastien RoccaSerra

python3.6

import os    
from chardet import detect

# get file encoding type
def get_encoding_type(file):
    with open(file, 'rb') as f:
        rawdata = f.read()
    return detect(rawdata)['encoding']

from_codec = get_encoding_type(srcfile)

# add try: except block for reliability
try: 
    with open(srcfile, 'r', encoding=from_codec) as f, open(trgfile, 'w', encoding='utf-8') as e:
        text = f.read() # for small files, for big use chunks
        e.write(text)

    os.remove(srcfile) # remove old encoding file
    os.rename(trgfile, srcfile) # rename new encoding
except UnicodeDecodeError:
    print('Decode Error')
except UnicodeEncodeError:
    print('Encode Error')

解决方案 5:

您可以使用这个衬垫(假设您想从utf16转换为utf8

    python -c "from pathlib import Path; path = Path('yourfile.txt') ; path.write_text(path.read_text(encoding='utf16'), encoding='utf8')"

您的$fileyourfile.txt的路径在哪里。

为了使其工作,您需要python 3.4或更新版本(现在可能您需要)。

下面是上述代码的更易读的版本

from pathlib import Path
path = Path("yourfile.txt")
path.write_text(path.read_text(encoding="utf16"), encoding="utf8")

解决方案 6:

这是一个Python3函数,用于将任何文本文件转换为 UTF-8 编码的文件。(无需使用不必要的包)

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]+'
')

您可以轻松地在循环中使用它来转换文件列表。

解决方案 7:

要猜测源编码,您可以使用file*nix 命令。

例子:

$ file --mime jumper.xml

jumper.xml: application/xml; charset=utf-8

解决方案 8:

将目录中的所有文件转换为 utf-8 编码。它是递归的,可以按后缀过滤文件。谢谢@Sole Sensei

# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple chardet
import os
import re
from chardet import detect


def get_file_list(d):
    result = []
    for root, dirs, files in os.walk(d):
        dirs[:] = [d for d in dirs if d not in ['venv', 'cmake-build-debug']]
        for filename in files:
            # your filter
            if re.search(r'(.c|.cpp|.h|.txt)$', filename):
                result.append(os.path.join(root, filename))
    return result


# get file encoding type
def get_encoding_type(file):
    with open(file, 'rb') as f:
        raw_data = f.read()
    return detect(raw_data)['encoding']


if __name__ == "__main__":
    file_list = get_file_list('.')
    for src_file in file_list:
        print(src_file)
        trg_file = src_file + '.swp'
        from_codec = get_encoding_type(src_file)
        try:
            with open(src_file, 'r', encoding=from_codec) as f, open(trg_file, 'w', encoding='utf-8') as e:
                text = f.read()
                e.write(text)
            os.remove(src_file)
            os.rename(trg_file, src_file)
        except UnicodeDecodeError:
            print('Decode Error')
        except UnicodeEncodeError:
            print('Encode Error')

解决方案 9:

这是我的强力方法。它还处理了输入中混合的 \n 和 \r\n。

    # open the CSV file
    inputfile = open(filelocation, 'rb')
    outputfile = open(outputfilelocation, 'w', encoding='utf-8')
    for line in inputfile:
        if line[-2:] == b'
' or line[-2:] == b'

':
            output = line[:-2].decode('utf-8', 'replace') + '
'
        elif line[-1:] == b'
' or line[-1:] == b'
':
            output = line[:-1].decode('utf-8', 'replace') + '
'
        else:
            output = line.decode('utf-8', 'replace') + '
'
        outputfile.write(output)
    outputfile.close()
except BaseException as error:
    cfg.log(self.outf, "Error(18): opening CSV-file " + filelocation + " failed: " + str(error))
    self.loadedwitherrors = 1
    return ([])
try:
    # open the CSV-file of this source table
    csvreader = csv.reader(open(outputfilelocation, "rU"), delimiter=delimitervalue, quoting=quotevalue, dialect=csv.excel_tab)
except BaseException as error:
    cfg.log(self.outf, "Error(19): reading CSV-file " + filelocation + " failed: " + str(error))

解决方案 10:

import codecs
import glob

import chardet

ALL_FILES = glob.glob('*.txt')

def kira_encoding_function():
    """Check encoding and convert to UTF-8, if encoding no UTF-8."""
    for filename in ALL_FILES:

        # Not 100% accuracy:
        # https://stackoverflow.com/a/436299/5951529
        # Check:
        # https://chardet.readthedocs.io/en/latest/usage.html#example-using-the-detect-function
        # https://stackoverflow.com/a/37531241/5951529
        with open(filename, 'rb') as opened_file:
            bytes_file = opened_file.read()
            chardet_data = chardet.detect(bytes_file)
            fileencoding = (chardet_data['encoding'])
            print('fileencoding', fileencoding)

            if fileencoding in ['utf-8', 'ascii']:
                print(filename + ' in UTF-8 encoding')
            else:
                # Convert file to UTF-8:
                # https://stackoverflow.com/q/19932116/5951529
                cyrillic_file = bytes_file.decode('cp1251')
                with codecs.open(filename, 'w', 'utf-8') as converted_file:
                    converted_file.write(cyrillic_file)
                print(filename +
                      ' in ' +
                      fileencoding +
                      ' encoding automatically converted to UTF-8')


kira_encoding_function()

来源:

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1988  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1446  
  随着信息技术的飞速发展,数据已成为企业和国家的核心资产。保障数据安全,是维护国家安全、社会稳定以及企业可持续发展的关键。在这一背景下,信创国产化操作系统逐渐崭露头角,其对数据安全的影响备受关注。信创国产化操作系统旨在实现信息技术领域的自主可控,减少对国外技术的依赖,从底层架构到上层应用构建起安全可靠的信息技术体系。深入...
信创国产化要求   0  
  信创产业作为近年来备受瞩目的领域,其发展态势对投资者具有极大的吸引力。探寻信创概念股中投资回报率最高的五家公司,对于投资者来说至关重要。这不仅能为他们的资金找到更具潜力的投向,也有助于把握行业发展的脉搏,在复杂多变的市场中获取丰厚的回报。随着信息技术的飞速发展以及国家对自主创新的高度重视,信创产业迎来了前所未有的发展机...
信创是什么意思   0  
  信创产业,即信息技术应用创新产业,旨在实现信息技术领域的自主可控,保障国家信息安全。近年来,信创产业发展势头迅猛,对传统行业的数字化转型产生了深远影响。传统行业在当今时代面临着诸多挑战,如市场竞争加剧、客户需求多样化等,数字化转型成为其提升竞争力、实现可持续发展的关键路径。而信创产业凭借其独特的技术优势和产业生态,为传...
信创国产化   0  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用