[DIR_NAME] For all files below Check if it is a text file with the character code defined in [TARGET_ENCODING_LIST], Output to the file name of [OUTPUT_NAME]. If it cannot be determined, it will be output as binary.
Windows8 + Python2.6 series
check_encoding.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: fileencoding=utf-8
import os , sys
DIR_NAME = 'C:\\Program Files\\'
OUTPUT_NAME = 'result_file_encoding_list.txt'
TARGET_ENCODING_LIST = [
'utf-8',
'shift-jis',
'euc-jp',
'iso2022-jp'
]
FLAG_STDOUT = True
#FLAG_STDOUT = False
import os, sys
write = sys.stdout.write
def guess_charset(data):
file = lambda d, encoding: d.decode(encoding) and encoding
for enc in TARGET_ENCODING_LIST:
try:
file(data, enc)
return enc
except:
pass
return 'binary'
out = open(OUTPUT_NAME, 'w')
for dirpath, dirs, files in os.walk(DIR_NAME):
for fn in files:
path = os.path.join(dirpath, fn)
fobj = file(path, 'rU')
data = fobj.read()
fobj.close()
try:
enc = guess_charset(data)
except:
continue
str = path + ',' + enc + '\n'
try:
if FLAG_STDOUT == True:
write(str)
out.write(str)
except:
continue
Exception handling is appropriate. If the file name contains Japanese characters, the characters will be garbled.
Recommended Posts