【问题标题】:Error using DictWriter/writerows to write data to CSV使用 DictWriter/writerows 将数据写入 CSV 时出错
【发布时间】:2012-04-23 12:45:25
【问题描述】:

问题:

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

ValueError: dict contains fields not in fieldnames: 1, 0, 0, 0, 0, 0, 1

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

说明

从这个 SO question 构建我的初始程序, 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

评论

我知道这不是免费的代码编写服务,但我们将不胜感激。我是否忘记了如何使用 writerows?根据我对阅读 csv.py 源代码的了解,它正在尝试将我的用户输入加入到结果中,当它们将被写入 CSV 时。我的目标是只写结果,而不是我的用户输入(这将是另一件事要学习)。我剥掉了 cmets,但请询问您是否需要解释。

资源

How to think like a computer scientist

DictWriter

【问题讨论】:

    标签: python csv


    【解决方案1】:
    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 2017-11-08
      • 2014-01-21
      • 2011-12-30
      • 2021-06-30
      相关资源
      最近更新 更多