在python中检查csv文件的索引

时间:2015-10-26 14:19:34

标签: python csv indexing

我需要找到一种方法,即csv文件将输入放在最高索引上。例如,我有三行填充信息,现在它必须开始将输入放在第四行,但我不知道如何做到这一点。

以下是我的代码,您也可以在pastebin找到:

__author__ = 'mar'

import csv
csvbestand="project.csv"

#This part is supposed to find the highest index
def indexchk():
    global index

    try:
        f = open(csvbestand, 'r')
        reader = csv.reader(f, delimiter=';')
        for i in csvbestand:

    except:
        print("lukt niet")

    finally:
        f.close()

#Here you can put your input which is then placed in the csv document. Now it needs to be put in a different row then the previous ones.
def user():
    try:
        f = open(csvbestand, 'a', newline='')
        writer = csv.writer(f, delimiter=';')
        #writer.writerow( ('Voornaam(s)', 'Achternaam', 'Geboortedatum', 'E-mailadres') )
        writer.writerow((index),(input("Voornaam(s): "),input("Achternaam: "),input("Geboortedatum: "),input("E-mailadres: ")))
    except BaseException:
            print("fout, kan bestand niet openen")

    finally:
        f.close()

indexchk()
user()

提前谢谢

2 个答案:

答案 0 :(得分:0)

只要您将文件打开到append而不是write,就会在文件的最后一行之后写入任何新行。

您的代码正确地将文件打开到append,因此您应该能够添加其他行,而无需先明确标识最后一行。

附加任何新行:

f = open(csvbestand, 'a')

覆盖整个文件:

f = open(csvbestand, 'w')

答案 1 :(得分:0)

如果我理解得很好,你会尝试在它的末尾写一个csv文件(从它的最后一行开始)?

yourfile = open('project.csv','a')
yourfile.write(TheStuffYouWantToWrite)
yourfile.close()

Here a summary of file manipulation