Python:替换CSV文件中的一个单元格

时间:2013-10-26 07:42:20

标签: python csv

我有一个CSV文件,其中包含一个我要编辑的单元格。

我可以编写一个非常简单的函数,例如,可以查找文件中的ID字段并返回有问题的ID行:

id = 3 #column number of the ID field

csvfile = open(os.path.join(LOCAL_FOLDER, "csvfile.csv"), "rU")
csvFile= csv.reader(csvfile, delimiter=",")

def lookup(ID):
    rowNo = 1
    for row in csvFile:
        if row[id] == ID:
            return rowNo
        else:
            rowNo += 1
    return 0

我想要做的是编写一个相应的replace函数,该函数将包含IDcolumn变量和data变量:

def replace(ID, col, data):
    row = lookup(ID)
    #use a CSV writer to replace the item at row, col with data

我不知道如何做到这一点,我可以找到的关于如何使用编写器的所有示例只显示如何完全重写整个.CSV文件,这不是我想要做的;我希望等效PUT而不是POST

1 个答案:

答案 0 :(得分:0)

fwiw,根据检查员G4dget的建议,我重写了我的代码如下:

LOCAL_FOLDER = os.getcwd()
CSV_FILE = "csvfile.csv"

def lookup(ID):
    csvfile = open(os.path.join(LOCAL_FOLDER, CSV_FILE), "rU")
    csvFile= csv.reader(csvfile, delimiter=",")
    rowNo = 1
    for row in csvFile:
        if row[id] == ID:
            csvfile.close()
            return rowNo
        else:
            rowNo += 1
    csvfile.close()
    return 0

def replace(ID, col, data):
    index = 1
    row = lookup(ID)
    if row == 0:
        return 0
    csvwritefile = open(os.path.join(LOCAL_FOLDER, "temp.csv"), "w")
    csvWriteFile = csv.writer(csvwritefile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) #obviously change this if you want a diff quoting format
    csvreadfile = open(os.path.join(LOCAL_FOLDER, CSV_FILE), "rU")
    csvReadFile= csv.reader(csvreadfile, delimiter=",")
    for readrow in csvReadFile:
        if index == row:
            temp = readrow
            temp[col] = data
            csvWriteFile.writerow(temp)
            index += 1
        else:
            index += 1
            csvWriteFile.writerow(readrow)

    csvwritefile.close()
    csvreadfile.close()
    os.rename(os.path.join(LOCAL_FOLDER, "temp.csv"), os.path.join(LOCAL_FOLDER, CSV_FILE))

    return 1