Z R
Z R

Reputation: 121

Looping over a CSV file, attempting to delete particular cells

Here's what I have so far:

import csv
fp = open('C:/TemporaryDataFiles/RawData.csv', 'w')
csvFile = csv.writer(fp)


for number, begin, end, test in rows:
    if len(test.split()) <= 100:
        print("Row deleted!")
        print(len(test.split()))
        stock=[]
        begin=[]
        end=[]
        test=[]


    else:
        RowsToWrite= [str(number), str(begin), str(end), str(test)]
        csvFile.writerows(RowsToWrite)

I'm trying to iterate over a large table, called rows, which has four subcomponents to it. It has number (representing a number of a product), the begin time, the end time, and a test column, which has a description inside of it.

I'm trying to see if test has fewer than 100 words in it. If it doesn't, then it goes to the else section of the if...else statement, then gets written to the RawData.csv file.

This doesn't generate any errors, however, it doesn't give the proper output either. There are a few entries, all under 100 words, which slip through.

I've tried as many iterations as I can think of, and I feel as if I'm missing something basic here.

Any assistance is appreciated.

Upvotes: 0

Views: 38

Answers (1)

cwahls
cwahls

Reputation: 753

I think writerows is looking for multiple rows, not just one. Do like RowsToWrite.append([str(number), str(begin), str(end), str(test)]), and then after the for loop use the csvFile.writerows(RowsToWrite). Keep your imports and everything, but the whole for loop would look like this:

RowsToWrite = []
for number, begin, end, test in rows:
    if len(test.split()) <= 100:
        print("Row deleted!")
        print(len(test.split()))
        number=''
        begin=''
        end=''
        test=''

    RowsToWrite.append([str(number), str(begin), str(end), str(test)])

csvFile.writerows(RowsToWrite)

I guess that the writerows method uses commas when writing to the file. Here's the full doc.

You could also write each row one at a time in the for loop (see docs).

Upvotes: 1

Related Questions