Ivan
Ivan

Reputation: 51

I'm calling a function twice, but it works only the first time

I have this problem. I made this fonction to make a couple of fixes on a csv file. It only works the first time I call it, but not the second time. Thanks for your help!

import csv

file = open('original.csv', 'r')
fileOut = open('fixed.csv', 'wb')

# Make a list out of the csv content
read = [x for x in csv.reader(file)]
writer = csv.writer(fileOut, delimiter=',', quoting=csv.QUOTE_NONE)

# Function to make changes to the csv
def rep(field, uno, dos):
    for x in read:
        x[field] = x[field].replace(uno, dos)
        writer.writerow(x)

# First call
rep(0, 'COMISARIA ', '')

# Second call
rep(4, 'AVDA', '')

fileOut.close()

Upvotes: 0

Views: 519

Answers (1)

acushner
acushner

Reputation: 9946

the problem lies in where you call writer. the first time you call it, it puts all the output into 'fixed.csv'. then, the second time you call the func, it adds the rows to the end of that file.

the solution would be to not call writer.writerow(x) in rep and instead do:

# Second call
rep(4, 'AVDA', '')

writer.writerows(read)
fileOut.close()

Upvotes: 1

Related Questions