您当前的位置:首页 > 电脑办公 > excel
| PPT | 电脑打字 | 计算机基础 | word | excel | Linux教程 |

自学教程:使用python将所有csv文件从编码ansi转换为utf8

51自学网 2021-11-27 19:15:31
  excel
这篇教程使用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文件 将每一行存为数组
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1