2012-08-09 6 views
2

나는 python web site에서이 스크립트를 복사 한 :이 스크립트를 실행하면파이썬 CSV 유니 코드 예를

import sqlite3 
import csv 
import codecs 
import cStringIO 
import sys 

class UTF8Recoder: 
    """ 
    Iterator that reads an encoded stream and reencodes the input to UTF-8 
    """ 
    def __init__(self, f, encoding): 
     self.reader = codecs.getreader(encoding)(f) 

    def __iter__(self): 
     return self 

    def next(self): 
     return self.reader.next().encode("utf-8") 

class UnicodeReader: 
    """ 
    A CSV reader which will iterate over lines in the CSV file "f", 
    which is encoded in the given encoding. 
    """ 

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): 
     f = UTF8Recoder(f, encoding) 
     self.reader = csv.reader(f, dialect=dialect, **kwds) 

    def next(self): 
     row = self.reader.next() 
     return [unicode(s, "utf-8") for s in row] 

    def __iter__(self): 
     return self 

class UnicodeWriter: 
    """ 
    A CSV writer which will write rows to CSV file "f", 
    which is encoded in the given encoding. 
    """ 

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): 
     # Redirect output to a queue 
     self.queue = cStringIO.StringIO() 
     self.writer = csv.writer(self.queue, dialect=dialect, **kwds) 
     self.stream = f 
     self.encoder = codecs.getincrementalencoder(encoding)() 

    def writerow(self, row): 
     self.writer.writerow([s.encode("utf-8") for s in row]) 
     # Fetch UTF-8 output from the queue ... 
     data = self.queue.getvalue() 
     data = data.decode("utf-8") 
     # ... and reencode it into the target encoding 
     data = self.encoder.encode(data) 
     # write to the target stream 
     self.stream.write(data) 
     # empty queue 
     self.queue.truncate(0) 

    def writerows(self, rows): 
     for row in rows: 
      self.writerow(row) 

, 나는이 오류가 :

Traceback (most recent call last): 
    File "makeCSV.py", line 20, in <module> 
    class UnicodeReader: 
    File "makeCSV.py", line 26, in UnicodeReader 
    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): 
AttributeError: 'module' object has no attribute 'excel' 

할 수있는 방법이 오류와 이유가 될 수있는 것 고쳐?

+0

어떤 버전의 파이썬입니까? 2603 –

+0

파이썬 2.7에 csv.excel이 있습니다. – torayeff

+0

hrm이 작동하기 전에 2.7, 여전히 남아 있습니다. http://docs.python.org/library/csv.html#csv.excel –

답변

6

이 모듈 csv은 생각하지 않습니다. stdlib csv 모듈 대신 가져 오는 경로에 csv.py가 없는지 확인하십시오.

(스크립트 내에서) csv.__file__을 인쇄하여 어디서 왔는지 확인할 수 있습니다. 그런 다음 잘못된 파일을 제거/이동하여 stdlib csv를 가져옵니다.

1

아마도 질문은 어리석은 짓입니다.하지만 삭제하는 대신 해답을 제시 할 가치가 있다고 생각합니다. 문제가있는 스크립트로 작업 디렉토리에 csv.py 스크립트를 만들었습니다. 그래서 파이썬 인터프리터가 파이썬 파일 경로에서 현재 작업 디렉토리의 라이브러리를 가져 오기 시작했다는 것을 이해했습니다. 이것이 문제였습니다.

+1

내 대답을 좋아하지 않아. : ( –

관련 문제