#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys, getopt, chardet
def main(argv):
inputfile = ''
try:
opts, args = getopt.getopt(argv,"hf:",["file="])
#print 'error'
except getopt.GetoptError:
print 'file_check.py -f <file>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'file_check.py -f <file>'
sys.exit()
elif opt in ("-f", "--file"):
inputfile = arg
print '输入的文件为:', inputfile
f = open(inputfile,'r')
data = f.read()
print chardet.detect(data)
sys.exit()
if __name__ == "__main__":
main(sys.argv[1:])
运行结果:
$ python file_check.py -f gb2312.csv
输入的文件为: gb2312.csv
{'confidence': 0.99, 'encoding': 'GB2312'}