2011-01-15 4 views
0

私はいくつかのファイルを処理していますが、処理中のログを作成したいと思います。私は各観測のキーと値を保持するために辞書を使ってログを作成し、その辞書をリスト(辞書のリスト)に追加しています。csv.dictWriter.writerow(somerow)を使用すると、行がスキップされないようにする方法はありますか?

ログを保存するには、Pythonのcsvモジュールを使用して辞書のリストを書き出します。当初、私はwriterowsを使用していたが、私は私が保管していた値のいくつかは、ASCII以外の何かある非常にまれにしかないという問題が発生した

例私の解決策は、tryを使用して辞書の私のリストを反復処理することでした

Investee\xe2\x80\x99s Share of Profits 

/問題辞書

for docnumb, item in enumerate(x[1]): 
    try: 
     dict_writer.writerow(item) 
    except UnicodeEncodeError: 
     missed.append(docnumb) 
     item 

スキップする文を除きしかし、これは、出力CSVファイルの各行に挿入される余分な行をもたらします。

value1 value2 value3 etc . . . 
#blank row 
value1 value2 value3 etc 

この動作を抑制する方法はわかりません。

私は次のように彼らはUnicodeWriterクラスを与えるhttp://docs.python.org/library/csv.html#csv-examples

でマニュアルを参照してくださいここで

import csv 
keyset=set([]) 
for item in x[1]: 
    keyset |=set(item.keys()) 
keys=list(keyset) 
logref=open(r'c:\December_2010_File_list.csv','w') 
dict_writer=csv.DictWriter(logref,keys) 

keyset |=set(item.keys()) 

答えて

1

得た方法についての詳細明快ありますので、もう少しコード:用

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) 
+0

おかげであなたの問題、なぜ私はドキュメントでこれを逃したのですか?私には脳細胞の1/2があるので – PyNEwbie

関連する問題