2013-12-12 6 views
0

를 사용하여 UTF8로 ANSI를 encodeing에서 모든 CSV 파일을 변환 파일을 읽고 ansi 인코딩을 utf8로 변환하지만 위 코드는 각 csv 파일의 읽기 경로 일뿐입니다. 그게 뭐가 잘못 됐는지 나는 모르겠다.내가 아래 파이썬 코드를 파이썬

+0

코드를 형식화하고 전체 오류 메시지를 게시하십시오. – graphite

+0

이제 오류 메시지가 표시됩니다. – user3024562

+2

먼저 [들여 쓰기] (https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Indentation)를 수정해야합니다. – graphite

답변

1

각 줄을 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. 
0

이 문서를 참조하십시오 : 당신이 문자열을해야하는 경우 http://docs.python.org/2/howto/unicode.html

, 당신은 특정 포맷으로 인코딩 할 것인지, 그것은 로 저장됩니다 말, 당신은 사용 s.encode() 아래

0

코드는 csv 파일을 나열하는 것입니다. 그것으로 아무 것도하지 않습니다. 읽어야 할 경우 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