当csv文件为n时,它将显示为空

2024-10-02 16:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个程序,该程序将把投票信息写入一个新的结果文件,在写入所有可用的投票选项之前,我需要检查文件是否为空。(否则,每次有人投票时,数据都会覆盖已经输入的结果)。我的问题是,当我运行这段代码时,它不会返回任何东西。在这里:

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

我应该得到一个声明说“空文件”或者“这里有数据”


Tags: 文件csv数据namein程序fordata
1条回答
网友
1楼 · 发布于 2024-10-02 16:23:24

当前您通过打开文件进行写入来销毁文件内容

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:

相关问题 更多 >