Python批量转换文件编码格式

#!/usr/bin/env python
# encoding: utf-8
"""
@author: wanwei
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
@contact: wei_wan
@software: pycharm
@file: batch_convert_encoding.py
@time: 2019/5/28 14:38
@desc:
"""

import os
import sys

in_enc="gbk"
out_enc="utf-8"


def convert(filename):
    in_enc = globals()['in_enc']
    out_enc = globals()['out_enc']
    try:
        with open(filename, 'r', encoding=in_enc) as f:
            content = f.read()
        with open(filename, 'w', encoding=out_enc) as f1:
            f1.write(content)
        print(filename + "................done")
    except IOError as err:
        print("{0}     ERROR:{1}".format(err.args[0], err.args[1]))
    except UnicodeDecodeError as err2:
        print(err2.with_traceback())


def explorer(dir):
    for root, dirs, files in os.walk(dir):
        for file in files:
            path = os.path.join(root, file)
            if os.path.isfile(path):
                convert(path)
            if os.path.isdir(path):
                explorer(path)


def judge_file_dir(path):
    if os.path.isfile(path):
        convert(path)
    if os.path.isdir(path):
        explorer(path)


def main():
    for path in sys.argv[1:]:
        path = os.path.join(path)
        judge_file_dir(path)


if __name__ == "__main__":
    sys.argv.append(r'E:\技术资料\python\数据分析')
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值