我调用了一个函数两次,但它只在第一次起作用

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

我有这个问题。我制作此功能是为了对 csv 文件进行一些修复。它只在我第一次调用它时有效,但第二次无效。 感谢您的帮助!

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()

问题出在你调用writer的地方。第一次调用它时,它会将所有输出放入 'fixed.csv'。然后,第二次调用 func 时,它会将行添加到该文件的末尾。

解决方案是不在 rep 中调用 writer.writerow(x) 而是执行:

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

writer.writerows(read)
fileOut.close()