-2

我有一个 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函数,该函数将接受一个ID,一个column变量和一个data变量:

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

我不知道如何做到这一点,我能找到的所有关于如何使用编写器的示例仅向您展示如何完全重写整个 .CSV 文件,这不是我想要做的;我想要一个等价的 aPUT而不是 a POST

4

1 回答 1

0

fwiw,根据inspectorG4dget的建议,我重写了我的代码如下:

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
于 2013-10-26T08:13:11.667 回答