Copying CSV File when integer exceeds maximum

264 views Asked by At

If this input exists in a specific row, for example DD in row WORD4 (row 3), the program will then ask them to enter an integer and if this is over a certain number it will write it including the line.

Something like so:

a0,a1,a2,a3,a4    
JA,BV,PA,DD,6

The error received I did receive was:

TypeError: writerows() takes exactly one argument (2 given) 

And

TypeError: can only concatenate list (not "str") to list 

Thanks to Joel Johnson and Stevieb for the solution to this problem!

The solution is as followed, Thanks Joel Johnson:

2

There are 2 answers

2
Joel Johnson On BEST ANSWER

First, you need to use with open('CSVFile2.csv', 'a') as f: to write anything to the file(if you want to keep any content already in CSVFile2.csv or use 'w' if you want to overwrite it).

Second, since you are only trying to write one row with format ['JA',BV','PA','DD','6'] use writer.writerow() instead of writer.writerows() else you will end up with J,A,B,V,P,A,D,D,6 as your output.

Third, simply append integer_input to row before passing it to writer.writerow() also note that it needs to be in str() format

If you have any other questions I would refer you to the docs here

example:

with open('CSVFile1.csv', "rb") as csvfile:
    a = csv.reader(csvfile, delimiter=',')
    for row in a:
        if user_input in row[3] and integer_input>5:
            with open('CSVFile2.csv', 'a') as f:
                new_row = row
                new_row.append(str(integer_input))
                writer = csv.writer(f)
                writer.writerow(new_row)
                f.close()
3
stevieb On

writerows() does only take one parameter. The below code appends the row[3] to the row, then the entire row is sent to writerow() as its only parameter. I've also moved the writer file to outside of the loop, otherwise if more than one match occurs, you'd be overwriting it on each iteration.

with open('CSVFile1.csv', 'rb') as csvfile:

    fh = csv.reader(csvfile)
    wfh = open('CSVFile2.csv', 'ab')

    for row in fh:
        if user_input in row[3] and int(integer_input) > 5:
            row.append(integer_input)
            writer = csv.writer(wfh)
            writer.writerow(row)

    wfh.close()