Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Iterating a dictwriter
#1
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))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question csv Dictwriter problems fsuedr2022 4 2,203 Oct-28-2020, 02:47 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020