: 내 입력을 1000001을 입력 할 때ValueError: dict contains fields not in fieldnames: 1, 0, 0, 0, 0, 0, 1
CSV 파일에 데이터를 쓸 writerows를 사용하여, 나는 현재 다음과 같은 오류를 참조
필드 이름은 CSV (history.csv)에는 올바르게 기록되지만 결과는 올바르게 기록되지 않습니다.
설명이 SO 질문에서 내 초기 프로그램의 오프
건물, Search a single column for a particular value in a CSV file and return an entire row.
직접 검색 데이터를 추적 할 수 있도록 검색 기능의 출력을 별도의 CSV 파일에 기록하려고합니다. 필자는 여전히 파이썬을 배우면서 CSV를 읽고 쓰는 것이 좋은 출발이 될 것이라고 생각했습니다. 윈도우 7 컴퓨터에
기능이 프로그램은 3 개 기능 (예, 쓰기 기능을 연습하고 싶었다 함께 내장되어
를 파이썬 3.2.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