問題:錯誤寫數據到CSV
當使用writerows將數據寫入到CSV文件,我目前看到下面的錯誤,當我進入1000001我輸入:
ValueError: dict contains fields not in fieldnames: 1, 0, 0, 0, 0, 0, 1
字段名正確寫入CSV(history.csv),但不是結果。
說明
建築了我的初步方案由這太問題, Search a single column for a particular value in a CSV file and return an entire row。
我試圖將搜索功能的輸出寫入單獨的CSV文件,以便讓我自己輕鬆地跟蹤搜索數據。由於我仍然在學Python,所以我覺得閱讀然後寫CSV會是一個好的開始。
詳細
Windows 7的計算機上使用Python 3.2.3
功能
該計劃是建有3個功能(是的,我想練習寫作功能,讓我知道這是否沒有意義):search
,csv_record
和main
。 search
功能來自原來的SO問題,csv_record
包含寫入代碼,而main
只是將它們連接在一起並要求用戶輸入。
樣本數據
1000001;Name here:1;1001;1;11;Item description here:1
1000002;Name here:2;1002;2;22;Item description here:2
1000003;Name here:3;1003;3;33;Item description here:3
1000004;Name here:4;1004;4;44;Item description here:4
1000005;Name here:5;1005;5;55;Item description here:5
1000006;Name here:6;1006;6;66;Item description here:6
1000007;Name here:7;1007;7;77;Item description here:7
1000008;Name here:8;1008;8;88;Item description here:8
1000009;Name here:9;1009;9;99;Item description here:9
代碼
import sys
import traceback
from csv import DictReader
from csv import DictWriter
from collections import namedtuple
def search(user_input):
raw_data = 'active.csv'
with open(raw_data, 'r', newline='') as open_data:
read_data = DictReader(open_data, delimiter=';')
item_data = namedtuple('item_data', read_data.fieldnames)
for row in (item_data(**data) for data in read_data):
if row.Item == user_input:
return row
return
def csv_record(search_output,record_value):
hist_file = 'history.csv'
record_positive = 'Record has been written to CSV file'
record_negative = 'Recording has been disabled'
if record_value == 1:
with open(hist_file, 'w', newline='') as history:
history_dw = DictWriter(history, delimiter='\t', fieldnames=search_output._fields)
history_dw.writeheader()
history_dw.writerows(search_output)
return record_positive
else:
return record_negative
def main():
failure = 'No matching item could be found. Please try again.'
recording = 1
item = input("Please enter your item code: ")
result = search(item)
records = csv_record(result,recording)
print(records)
return
評論
我知道這是不是一個免費的代碼編寫服務,但任何幫助,將不勝感激。有什麼我忘記如何使用作家?根據我對讀取csv.py源代碼的理解,它將嘗試將用戶輸入加入結果中,以便將結果寫入CSV。我的目標是隻寫結果,而不是我的用戶輸入(這是另一個要學習的東西)。我刪除了評論,但請詢問是否需要解釋。
資源
How to think like a computer scientist