2016-12-09 71 views
0

test.csv中的數據僅包含國家和部門。這將填寫在writer.writerow(data)使用字典在Python中使用列寫入數據

我已經添加了額外的列使用:writer = csv.DictWriter然後writer.writeheader()

我想填寫使用字典詞典中的數據添加的列。數據將在該列中填滿大約200行。

import json 
import csv 

def parse_file(input): 
    with open(input, 'r') as input: 
     content = input.readlines() 
     csv_file = open('test.csv', 'wb+') 

     writer = csv.DictWriter(csv_file, fieldnames=["employee_id", "firstname", "lastname", "country", "dept"], delimiter=',') 
     writer.writeheader() 

     dicts = [{'employee_id':'123456', 'firstname':'Tom', 'lastname':'jones' }] 

     for line in content: 
      line_segments = line.split('\t') 

      data = json.loads(line_segments[0]) 

      writer.writerow(data) 

      for d in dicts: 
       print(d['id']) 
       writer.writerow([d['employee_id'],d['firstname'],d['lastname']]) 

錯誤:

Traceback (most recent call last): 
    File "parse_file.py", line 36, in <module> 
    parse_input_file(args.input_file) 
    File "parse_file.py", line 25, in parse_input_file 
    writer.writerow([d['femployee_id'],d['firstname'],d['lastname']]) 
    File "C:\Users\\AppData\Local\Continuum\Miniconda3\csv.py", line 152, in writerow 
    return self.writer.writerow(self._dict_to_list(rowdict)) 
    File "C:\Users\\AppData\Local\Continuum\Miniconda3\\lib\csv.py", line 148, in _dict_to_list 
    + ", ".join([repr(x) for x in wrong_fields])) 
ValueError: dict contains fields not in fieldnames: '123456', 'Tom', 'Jones' 
+0

'類型的字典= [{ '僱員標識': '123456', '姓': '湯姆', '姓氏': '瓊斯'} ]'錯誤的想法cos'employee_id'是'123456',所以標題是靜態的,你可以只寫值!需要寫'[「123456」,「湯姆」,「瓊斯」]'不包括鍵! – dsgdfg

回答

1

正如追溯狀態的錯誤:

ValueError: dict contains fields not in fieldnames: 

是來自查詢字典包含比你在DictWriter指定的字段名稱更關鍵構造函數。在csv.DictWriter

,已指定字段名爲:

fieldnames=["employee_id", "firstname", "lastname", "country", "dept"] 

但你在這行通過只有三個字典值:

for d in dicts: 
    print(d['id']) 
    writer.writerow([d['employee_id'],d['firstname'],d['lastname']]) 

你需要的是更新用字典命名爲dicts,像這樣:

dicts = {'employee_id':'123456', 'firstname':'Tom', 'lastname':'jones','country':'some_country_name', 'dept':'some_dept' } 

最後更新的代碼應該是這個樣子:

import json 
import csv 

def parse_file(input): 
    with open(input, 'r') as input: 
     content = input.readlines() 
     csv_file = open('test.csv', 'wb+') 

     writer = csv.DictWriter(csv_file, fieldnames=["employee_id", "firstname", "lastname", "country", "dept"], delimiter=',') 
     writer.writeheader() 

     dicts = {'employee_id':'123456', 'firstname':'Tom', 'lastname':'jones','country':'some_country_name', 'dept':'some_dept' } 

     for line in content: 
      line_segments = line.split('\t') 
      data = json.loads(line_segments[0]) 
      writer.writerow(data) 
      writer.writerow(dicts) 
+0

感謝您的支持。但問題是「國家」,「部門」的數據來自parse_file(輸入)處的輸入文件。字典中指定的前三列是我正在添加的列 – Sam

+0

有沒有辦法將某些東西放在這些列中,以便它們被忽略?並且爲每一行寫出字典中給出的值? – Sam

+0

我可以在'some_country_name writer.fileldnames [3]'中添加一些內容嗎? – Sam