使用python的chardet库获得文件编码并修改编码

yipeiwu_com5年前Python基础

首先需要安装chardet库,有很多方式,我才用的是比较笨的方式:sudo pip install chardet

复制代码 代码如下:

#!/usr/bin/env python
# coding: UTF-8
import sys
import os
import chardet

 
def print_usage():
  print '''usage:
  change_charset [file|directory] [charset] [output file]\n
  for example:
    change 1.txt utf-8 n1.txt
    change 1.txt utf-8
    change . utf-8
    change 1.txt
'''
def get_charset(s):
  return chardet.detect(s)['encoding']

 
def remove(file_name):
  os.remove(file_name)

 
def change_file_charset(file_name, output_file_name, charset):
  f = open(file_name)
  s = f.read()
  f.close()

  if file_name == output_file_name or output_file_name == "":
    remove(file_name)

  old_charset = get_charset(s)
  u = s.decode(old_charset)

  if output_file_name == "":
    output_file_name = file_name
  f = open(output_file_name, 'w')
  s = u.encode(charset)
  f.write(s)
  f.close()

 
def do(file_name, output_file_name, charset):
  if os.path.isdir(file_name):
    for item in os.listdir(file_name):
      try:
        if os.path.isdir(file_name+"/"+item):
          do(file_name+"/"+item, "", charset)
        else:
          change_file_charset(file_name+"/"+item, "", charset)
      except OSError, e:
        print e
  else:
    change_file_charset(file_name, output_file_name, charset)

 
if __name__ == '__main__':
  length = len(sys.argv)

  if length == 1:
    print_usage()
  elif length == 2:
    do(sys.argv[1], "", "utf-8")
  elif length == 3:
    do(sys.argv[1], "", sys.argv[2])
  elif length == 4:
    do(sys.argv[1], sys.argv[3], sys.argv[2])
  else:
    print_usage()

相关文章

在Python中使用M2Crypto模块实现AES加密的教程

 AES(英文:Advanced Encryption Standard,中文:高级加密标准),是一种区块加密标准。AES将原始数据分成多个4×4字节矩阵来处理,通过预先定义的...

CentOS下Python3的安装及创建虚拟环境的方法

CentOS下Python3的安装及创建虚拟环境的方法

安装python3 一、安装需要编译的关联库 yum instal -y zlib zlib-devel   (根据自己系统的情况,安装需要的关联库,同样用yum安装...

python aiohttp的使用详解

python aiohttp的使用详解

1.aiohttp的简单使用(配合asyncio模块) import asyncio,aiohttp async def fetch_async(url): print(url)...

Python文本相似性计算之编辑距离详解

Python文本相似性计算之编辑距离详解

编辑距离 编辑距离(Edit Distance),又称Levenshtein距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数。编辑操作包括将一个字符替换成另一个字符,插入一...

python获取当前文件路径以及父文件路径的方法

python获取当前文件路径以及父文件路径的方法

#当前文件的路径 pwd = os.getcwd() #当前文件的父路径 father_path=os.path.abspath(os.path.dirname(pwd)+os.p...