2017-08-30 47 views
0

我試圖用Python將.txt文件轉換爲csv文件。這TXT不是conventionnal(至少我從來沒有見過類似的東西,它基本上是這樣的: key a: foo key b: bar $$$ $$$ key a: foo1 key b: bar1 $$$ $$$ key a: foo2 key b: bar2 在Python中讀取非標準數據庫

我只是希望得到以下CSV: foo, bar foo1, bar1 foo2, bar2

我有沒有困難做到這一點只是簡單地通過文件作爲一個字符串和分裂,但我想知道是否有一個更優雅的方式來做到這一點使用現有的庫,例如 在此先感謝!

回答

0

這就是我如何手動無論如何:

with open('input.txt', 'r') as f: 
    file_content = f.read() 
raw_res = file_content.split('$$$\n$$$\n') 

res = [] 

for item in raw_res: 
    item_dict = {} 
    keyvals = item.split('\n') 
    for keyval in keyvals: 
     if keyval != '' and ':' in keyval: 
      key, val = keyval.split(':', 1) 
      item_dict[key] = val.replace(",", " ") ## In order to ensure that val won't break the csv formatting later 
    res.append(item_dict) 
keys = res[0].keys 
with open('output.csv', 'w') as output_file: 
    dict_writer = csv.DictWriter(output_file, keys) 
    dict_writer.writeheader() 
    dict_writer.writerows(res)