使用DictWriter / writerows将数据写入CSV时出错

时间:2012-04-23 12:45:26

标签: python csv

问题:

当使用writerows将数据写入CSV文件时,当我输入1000001输入时,我当前看到以下错误:

  

ValueError:dict包含不在字段名中的字段:1,0,0,0,0,0,1

字段名称正确写入CSV(history.csv),但不能写入结果。

描述

从这个SO问题构建我的初始程序, 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个函数构建(是的,我想练习编写函数。如果这没有意义,请告诉我):searchcsv_recordmainsearch函数来自最初的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

DictWriter

1 个答案:

答案 0 :(得分:0)

file1 = open( DATA_DIR + "/final_file.csv", "w")
fileWriter = csv.writer(file1 , delimiter=",",quotechar='"', quoting=csv.QUOTE_MINIMAL)
Header =['Id','Date']#.enter the fields names in that 
fileWriter.writerow(Header)
for x in output:
        temp =[x['Id'],x['Date']]
        fileWriter.writerow(temp)
file1.close()