这篇教程使用python将所有csv文件从编码ansi转换为utf8写得很实用,希望能帮到您。
import os
from os import listdir
def find_csv_filenames(path_to_dir, suffix=".csv" ):
path_to_dir = os.path.normpath(path_to_dir)
filenames = listdir(path_to_dir)
#Check *csv directory
fp = lambda f: not os.path.isdir(path_to_dir+"/"+f) and f.endswith(suffix)
return [path_to_dir+"/"+fname for fname in filenames if fp(fname)]
def convert_files(files, ascii, to="utf-8"):
for name in files:
print "Convert {0} from {1} to {2}".format(name, ascii, to)
with open(name) as f:
for line in f.readlines():
pass
print unicode(line, "gb2312").encode("utf-8")
csv_files = find_csv_filenames('/path/to/csv/dir', ".csv")
convert_files(csv_files, "gb2312") #gb2312 is my ascii coding. Replace with your coding. 使用python实现批量转换文件编码格式 python 读取excel文件 将每一行存为数组 |