python文本编码转换_python转换文件编码

这是一个Python脚本,用于批量将指定目录下非.bak文件的编码转换为UTF-8。在转换前,它会创建源文件的备份,并且只处理文本文件,忽略二进制文件。在遇到解码错误时,脚本会记录错误并继续处理其他文件。要运行脚本,需提供目标目录作为参数。
摘要由CSDN通过智能技术生成

每次在更新主题或者是wordpress的时候,经常会出现乱码,发现是文件的编码格式有问题,都不是utf-8格式,但是因为文件太多,懒得手动去修改,固写一个脚本程序来修改整个目录。

#-*- coding: utf-8 -*-

__author__ = 'L'

import sys

import os

import stat

import codecs

import chardet

import shutil

utf8_encoder = codecs.lookup('utf-8')

def change_file_code_to_uft8(path):

for item in os.listdir(path):

sub_path = os.path.join(path, item)

mode = os.stat(sub_path)[stat.ST_MODE]

if stat.S_ISDIR(mode):

continue

#change_file_code_to_uft8(sub_path)

else:

if (False == sub_path.endswith('.bak')):

print(sub_path)

with open(sub_path, "rb") as file_handle:

f = chardet.detect(file_handle.read())

print(f)

#print(f['encoding'])

if ('utf-8' != f['encoding'] and False == sub_path.endswith('.bak')):

new_file = sub_path + '.bak'

if (not os.path.exists(new_file)):

shutil.copyfile(sub_path, new_file)

#file_handle = codecs.open(sub_path, 'r', 'gbk')

file_handle = codecs.open(sub_path, 'r', f['encoding'])

try:

context = file_handle.read()

utf8_context = utf8_encoder.encode(context, 'ignore')

with open(sub_path, "wb") as file_handle:

file_handle.write(utf8_context[0])

except UnicodeDecodeError as err:

s = sys.exc_info()

print("Error '%s' happended on line %d" % (s[1], s[2].tb_lineno))

pass

if (False == sub_path.endswith('.bak')):

with open(sub_path, "rb") as file_handle:

f = chardet.detect(file_handle.read())

print(f['encoding'])

if len(sys.argv) >= 2:

current_path = sys.argv[1]

else:

print('please input path.')

sys.exit(0)

change_file_code_to_uft8(current_path)

上面的代码中没有使用递归修改,因为我只想修改目录下面的文件,如果你想递归修改,则可以把continue修改成下面注释的语句。而且对于二进制文件修改起来有问题,最好只是修改文本文件的编码。当然也可以指定后缀名来修改。怕修改文件可能出现错误,故在修改之前,先做了一下备份,如果修改之后没有问题,可以再写个脚本删除之,或者也可以直接在转化成功之后删除。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值