2

Issue:

When using writerows to write data to a CSV file, I currently see the following error when I enter 1000001 for my input:

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

The fieldnames write correctly to the CSV (history.csv) but not the results.

Description

Building off of my initial program from this SO question, Search a single column for a particular value in a CSV file and return an entire row.

I am trying to write the output from the search function to a separate CSV file in order to allow myself to easily track search data. As I am still learning Python, I felt that reading and then writing a CSV would be a good start.

Details

Using Python 3.2.3 on a Windows 7 computer

Functions

The program is built with 3 functions (yes, I wanted to practice writing functions. Let me know if this doesn't make sense): search, csv_record, and main. The search function comes from the original SO question, csv_record contains the writing code, and main just connects them all and asks for user input.

Sample Data

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

Code

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

Comments

I know that this is not a free code writing service, but any help would be appreciated. Is there something I am forgetting about how to use writerows? From what I understand about reading the source of csv.py, it is trying to join my user input to the results when they will be written to the CSV. My goal is to only write the results, not my user input (that will be another thing to learn). I stripped the comments but please ask if you need anything explained.

Resources

How to think like a computer scientist

DictWriter

Community
  • 1
  • 1
TheGreatFox
  • 53
  • 1
  • 4

1 Answers1

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()
Mohan
  • 9
  • 7