Python-在CSV文件中编辑特定的单元格 [英] Python - Edit specific cell in CSV file

查看:56
本文介绍了Python-在CSV文件中编辑特定的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Python创建了一个测验游戏,它还包含一个登录和注册程序,但是我试图添加一个计分系统.

I have created a quiz game in Python that also contains a login and register program however I'm trying to add a scoring system.

目前,我已将CSV文件设置如下:

Currently, I have the CSV file set out like this:

username,password,score

创建帐户时,分数设置为0,并在您使用以下方式登录时加载:

When you create an account the score is set to 0 and is loaded when you log in using:

for row in users:
     if username == row[0]:
         currentScore = row[2]
         currentScore = int((currentScore))

这会从CSV文件中获取用户的高分.但是,当游戏结束时,我可以使用此设置来确定他们的新分数是否高于旧分数:

This grabs the users high score from the CSV file. However when a game finishes I have this setup to determine if their new score is higher than there old score or not:

if int(score) > int(currentScore):
    currentscore = score

然后我需要它来打开数据库,找到正在玩的用户,并用新的分数更新那里的分数.我该怎么做?我试图让csv编辑特定的行,但是它似乎不起作用.

I then need it to open the database and find the user that is playing and update there score with the new one. How would I do this? I have tried to get csv to edit a certain row but it doesn't seem to work.

完整代码可在此处找到: https://pastebin.com/q07qazJA

Full code can be found here:https://pastebin.com/q07qazJA

推荐答案

TL; DR

if int(score) > int(currentScore):
    currentscore = score

    r = csv.reader(open('users.csv'))
    lines = list(r)
    for n, line in enumerate(lines):
        if [username, password] == list(line):
            break
    lines[n] = username, password, score

    writer = csv.writer(open('users.csv', 'w'))
    writer.writerows(lines)

quiz = False

说明:由于读取和写入文件的同一行不切实际,因此需要分两步进行编辑,因此首先打开 csv 文件,读取并保存将其保存到列表中,再编辑列表,然后再次打开文件 ,将编辑后的列表写回到 csv .

Explanation: Editing a row will need to be done in two steps since it's not practical to read and write to the same line of the file, so first open the csv file, read and save the data it to a list, edit the list, then open the file again to write the edited list back to the csv.

这篇关于Python-在CSV文件中编辑特定的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆