Search code examples
pythonpython-2.7csvpython-2.xfile-writing

CSV Writing to File Difficulties


I am supposed to add a specific label to my CSV file based off conditions. The CSV file has 10 columns and the third, fourth, and fifth columns are the ones that affect the conditions the most and I add my label on the tenth column. I have code here which ended in an infinite loop:

import csv
import sys

w = open(sys.argv[1], 'w')
r = open(sys.argv[1], 'r')

reader = csv.reader(r)
writer = csv.writer(w)

for row in reader:
    if row[2] or row[3] or row[4] == '0':
        row[9] == 'Label'
        writer.writerow(row)

w.close()
r.close()

I do not know why it would end in an infinite loop.

EDIT: I made a mistake and my original infinite loop program had this line:

w = open(sys.argv[1], 'a')

I changed 'a' to 'w' but this ended up erasing the entire CSV file itself. So now I have a different problem.


Solution

  • You have a problem here if row[2] or row[3] or row[4] == '0': and here row[9] == 'Label', you can use any to check several variables equal to the same value, and use = to assign a value, also i would recommend to use with open.

    Additionally you can't read and write at the same time in csv file, so you need to save your changes to a new csv file, you can remove the original one after and rename the new one using os.remove and os.rename:

    import csv
    import sys    
    import os
    
    with open('some_new_file.csv', 'w') as w, open(sys.argv[1], 'r') as r:
        reader, writer = csv.reader(r), csv.writer(w)
        for row in reader:
            if any(x == '0' for x in (row[2], row[3], row[4])):
                row[9] = 'Label'
            writer.writerow(row)
    
    os.remove('{}'.format(sys.argv[1]))
    os.rename('some_new_file.csv', '{}'.format(sys.argv[1]))