Python Forum

Full Version: Iterating a dictwriter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The below code behaves very strangely and unexpectedly in a few places. In the for loop, the loop always selects the first row (Invoice Amount) in the CSV file even though I know the loop is iterating properly (it increments and exits at 'row_count'). I would expect it to iterate to the next Invoice Amount (i.e. the next row) and get that value, thus looping through all values. Note that 'redflag_list' is a list I created outside the function - that is properly created.

Also, the writerow() appends to the end of the last row of the CSV file and adds 'row_count' number of times (either the word 'yes' or the word 'no' depending on the condition) thereafter. I know I am using append, i.e. "open(out_file, 'a', newline='')", but, if I try "open(out_file, 'w', newline='')" it completely overwrites the CSV leaving nothing in it. Thank you

with open(out_file, 'a', newline='') as csvfile:
    row_count = sum(1 for row in csv.reader(open(out_file)))
    writer = csv.DictWriter(csvfile, fieldnames=['Transaction Date',
            'Vendor ID Number', 'Purchase Order Date', 'Change Order',
            'Product ID Number', 'Unit Price', 'Quantity', 'Description',
            'Purchase Order Amount', 'Invoice Date',
            'Invoice Number', 'Invoice Amount', 'Payment Date', 'Payment Amount', 'Red_flag'], delimiter=',')
    #numline = len(list(csvfile))
    print(row_count)
    yes_count = 0
    no_count = 0
    for _ in range(row_count):
        invoice_number = row['Invoice Number']
        if invoice_number in redflag_list:
            yes_count = yes_count + 1
            writer.writerow({'Red_flag': 'yes'})
        else:
            no_count = no_count + 1
            writer.writerow({'Red_flag' : 'no'})
    print('Yes count is ' + str(yes_count))
    print('No count is ' + str(no_count))