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

该博客介绍了一种在Python中将混合格式的文件转换为UTF-8编码的方法。通过尝试不同的源格式并使用`chardet.universaldetector`库来检测文件的原始编码,实现了自动转换功能。
摘要由CSDN通过智能技术生成

谢谢你的回复,很管用!

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值