Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python将所有csv文件从ansi编码转换为utf8_Python_Csv_Utf 8 - Fatal编程技术网

使用python将所有csv文件从ansi编码转换为utf8

使用python将所有csv文件从ansi编码转换为utf8,python,csv,utf-8,Python,Csv,Utf 8,我有如下python代码: import os from os import listdir def find_csv_filenames( path_to_dir, suffix=".csv" ): filenames = listdir(path_to_dir) return [ filename for filename in filenames if filename.endswith( suffix ) ] #always got the error this

我有如下python代码:

import os
from os import listdir

def find_csv_filenames( path_to_dir, suffix=".csv" ):
    filenames = listdir(path_to_dir)
    return [ filename for filename in filenames if filename.endswith( suffix ) ]
    #always got the error this below code
filenames = find_csv_filenames('C:\casperjs\project\teleservices\csv')
for name in filenames:
    print name
我遇到了错误:

filenames = find_csv_filenames('C:\casperjs\project\teleservices\csv')
Error message: `TabError: inconsistent use of tabs and spaces in indentation`
我需要:我想读取所有csv文件,并将其从编码ansi转换为utf8,但上面的代码只是每个csv文件的读取路径。我不知道它出了什么问题?

请参阅文档:


如果您需要一个字符串,比如说它存储为s,您希望将其编码为特定格式,您可以使用s.encode()

下面将转换ascii文件中的每一行:

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, "cp866").encode("utf-8")    

csv_files = find_csv_filenames('/path/to/csv/dir', ".csv")
convert_files(csv_files, "cp866") #cp866 is my ascii coding. Replace with your coding.

您的代码只是列出csv文件。它和它没有任何关系。如果需要阅读,可以使用该模块。如果需要管理编码,可以执行以下操作:

import csv, codecs
def safe_csv_reader(the_file, encoding, dialect=csv.excel, **kwargs):
    csv_reader = csv.reader(the_file, dialect=dialect, **kwargs)
    for row in csv_reader:
        yield [codecs.decode(cell, encoding) for cell in row]

reader = safe_csv_reader(csv_file, "utf-8", delimiter=',')
for row in reader:
    print row

请格式化您的代码并发布完整的错误消息。好的,谢谢。现在我已经向您显示了错误消息。您应该首先修复。格式化后错误是否消失了?