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