Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 335
Reginsmal Avatar asked Feb 12 '16 02:02

Reginsmal


People also ask

Why is my CSV file not working?

Common issues with importing a CSV (and the work-arounds to fix them) The most common CSV import errors include: The file size is too large - The CSV import tool of the program you're using might have a file size requirement. To reduce the file size, you can delete unnecessary data values, columns, and rows.

Why does my exported CSV data get converted to weird formats?

Instead, this is due to the way Excel and other spreadsheet programs open a CSV file and display the data therein. Basically, spreadsheet programs are designed to be used for calculation purposes, so they tend to apply mathematical formats to numbers when the CSV file is opened directly into the program.

What is the correct format for a CSV file?

CSV , or Comma-separated Values, is an extremely common flat-file format that uses commas as a delimiter between values. Anyone familiar with spreadsheet programs has very likely encountered CSV files before - they're easily consumed by Google Spreadsheet, Microsoft Excel, and countless other applications.


1 Answers

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]))
like image 171
midori Avatar answered Sep 22 '22 10:09

midori