csv文件显示为空,而不是

时间:2016-12-07 17:25:13

标签: python csv

我创建的程序会将投票中的信息写入新文件以获取结果,我需要在写入所有可用的投票选项之前检查文件是否为空。 (否则,每次投票时,数据都会覆盖已输入的结果)。我的问题是,当我运行这段代码时,它没有返回任何内容。这是:

def VOTE1():
        Data = ("VOTE")
        voteChoice = OptionAmount.get()
        with open('EXISTINGVOTE.CSV') as infile:
            reader = csv.DictReader(infile)
            for row in reader:
                if voteChoice == row['TITLE NAME']:
                    f = open('{}.csv'.format(row['TITLE NAME']), "w")
                    f.close()
                    with open('{}.csv'.format(row['TITLE NAME']), "r") as f:
                        VoteRead = csv.reader(f, delimiter=",")
                        for row in VoteRead:
                            for field in row:
                                if field == Data:
                                    print("Empty file")
                                else:
                                    print("There is data in here")
                else:
                    print("Not this one")

我应该得到一个声明说'#34;清空文件"或者"这里有数据"

1 个答案:

答案 0 :(得分:0)

目前您通过打开文件来销毁文件内容......

f = open('{}.csv'.format(row['TITLE NAME']), "w")

...然后你读了一个空的新文件。

open('{}.csv'.format(row['TITLE NAME']), "r") as f

您可能想要做的是打开文件以附加数据:

if voteChoice == row['TITLE NAME']:
    # two lines deleted
    with open('{}.csv'.format(row['TITLE NAME']), "a") as f: