【问题标题】:CSV files in python - how to append to certain element in a rowpython中的CSV文件 - 如何附加到一行中的某个元素
【发布时间】:2021-01-17 15:54:04
【问题描述】:

对于我的计算机科学课程,我正在做一个骰子游戏,并使用 CSV 文件来存储用户名、密码和分数。到目前为止,我完成了用户名和密码部分,但我正在努力添加与用户名行相关的分数 - 例如,当用户使用用户名“emily”登录时,该行包含用户名“ emily”密码和之后的分数。如何将分数添加到该行中的特定元素,以便用户名与分数相关联?到目前为止,我已经完成了整个游戏。

任何帮助将不胜感激

谢谢

import random
import csv

player2_check1=0
player2_check2=0

player1_score=0
player2_score=0

rounds=0

login_p1=False
login_p2=False

player1=""
player2=""

def login_p1():

    global player1
    #authentication for p1
    username_p1=input("Username P1: ")
    password_p1 = input("Password P1 ")
    with open('data.txt') as csv_file:
        userdata = csv.reader(csv_file, delimiter=',')
        for row in userdata:
            if username_p1 == row[0] and password_p1 == row[1]:
                login=True
                player1=username_p1
                print("Welcome Player 1. You've been logged in!")
                login_p2()
                break
        else:
            login=False
            if login==False:
                print("Searching...")
                print("Not Found")
                login_p1()

def login_p2():

    global player2
    #authentication for p2
    username_p2=input("Username P2: ")
    password_p2 = input("Password P2 ")
    with open('data.txt') as csv_file:
        userdata = csv.reader(csv_file, delimiter=',')
        for row in userdata:
            if username_p2 == row[0] and password_p2 == row[1]:
                login=True
                player2=username_p2
                print("Welcome Player 2. You've been logged in!")
                player1_game()
                break
            else:
                login=False
                if login==False:
                    print("Searching...")
                    print("Not Found")

def player1_game():
    player1_check1 = 0
    player1_check2 = 0
    running_total = 0

    global player1_score
    global player1
    global rounds

    while rounds < 3:
        input(player1+", please click enter to roll the dice...")
        dice1=random.randint(1,6)
        print("\nYou scored: "+str(dice1))
        player1_check1=player1_check1+dice1

        input(player1+", please click enter to roll the dice again...")
        dice2=random.randint(1,6)
        print("\nYou scored: "+str(dice2))
        player1_check2=player1_check2+dice2

        runningtotal=player1_check1+player1_check2
        rounds = rounds + 1
        print ("Round number", rounds)

        if runningtotal%2==0:
            player1_score=player1_score+int(10)
            print(player1+" Got 10 Points!")
            print("\nYour new total score is: "+str(player1_score))
            print(" ")
        
            player2_game()

        elif runningtotal%2 != 0:
            print("Oh No! You Scored an Odd Number!")

            if player1_score<5:
                player1_score=0
                print("\nYour new total score is: "+str(player1_score))
                player2_game()

            else:
                player1_score=player1_score-5
                print("\nYour new total score is: "+str(player1_score))
                player2_game()

    if rounds==3:
        winner()
        
def player2_game():
    player2_check1 = 0
    player2_check2 = 0
    running_total = 0
    
    global player2_score
    global player2

    input(player2+", please click enter to roll the dice...")
    dice1=random.randint(1,6)
    print("\nYou scored: "+str(dice1))
    player2_check1=player2_check1+dice1

    input(player2+", please click enter to roll the dice again...")
    dice2=random.randint(1,6)
    print("\nYou scored: "+str(dice2))
    player2_check2=player2_check2+dice2

    runningtotal=player2_check1+player2_check2

    if runningtotal%2==0:
        player2_score=player2_score+int(10)
        print(player2+" Got 10 Points!")
        print("\nYour new total score is: "+str(player2_score))
        print(" ")

        player1_game()

    elif runningtotal%2 != 0:
        print("Oh No! You Scored an Odd Number!")

        if player2_score<5:
            player2_score=0
            print("\nYour new total score is: "+str(player2_score))
            
            player1_game()
            
        else:
            player2_score=player1_score-5
            print("\nYour new total score is: "+str(player2_score))

            player1_game()

def winner():

    global player1_score
    global player2_score
    global player1
    global player2

    if player1_score>player2_score:
        print("\nCongrats "+player1+", you won the game!")
        
    elif player2_score>player1_score:
        print("\nCongrats "+player2+", you won the game!")
        
    elif player2_score==player1_score:
        print("\nLooks like you both tied!")
        print("Whoever gets a higher dice wins!")
        tiegame()

def tiegame():

    player1_tie=0
    player2_tie=0

    global player1_score
    global player2_score
    global player1
    global player2

    print("\nLooks like you both tied!")
    input(player1+", Please click enter to roll dice...")
    tie1=random.randint(1,6)
    player1_tie=player1_tie+tie1
    print(" ")
    print(player1+" scored: "+str(player1_tie))

    print(" ")
    input(player2+", Please click enter to roll dice...")
    tie2=random.randint(1,6)
    player2_tie=player2_tie+tie2
    print(" ")
    print(player2+" scored: "+str(player2_tie))

    if player1_tie>player2_tie:
        print("\nCongrats "+player1+", you won the game!")
    elif player2_tie>player1_tie:
        print("\nCongrats "+player2+", you won the game!")
    elif player1_tie==player2_tie:
        tiegame()

login_p1()

【问题讨论】:

标签: python csv append


【解决方案1】:

首先,您可以像这样读取二维数组中的所有 csv 数据:

def get_users_data_array(file_name):
    users_data=[]
    csvreader = csv.reader(file_name, delimiter=',')
    for row in csvreader:
        users_data.append(row)
    return users_data

users_data 包含以下格式的所有行:[[row_1_col_1,row_1_col_2,...],[row_2_col_1,row_2_col_2,..],...]

每当您想更新/写入用户的分数时。您将首先更新users_data 数组中用户名的分数,然后将更新后的users_data 写入文件中。

def update_score(users_data,username,score):
    for user_data in users_data:
        # if we have found a user
        if users_data[0]==username:
            # update/write the scrore
            users_data[2]=score
    return users_data

def write_updated_data(file_name,users_data):
    with open(file_name, mode='w') as users_data_file:
        csvwriter = csv.writer(users_data_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        csvwriter.writerows(users_data)

总而言之,您可以通过以下方式使用上述功能:

# Reading data
users_data= get_users_data_array('users_data.csv')

# Initializing username and score
player1_username, player1_score="emily", 23
player2_username, player2_score="adam", 45

# Updating scores in the users_data array
users_data = update_score(users_data,player1_username,player1_score)
users_data = update_score(users_data,player2_username,player2_score)

# Writing the users_data array in to the csv file
write_updated_data(file_name= "users_data.csv",users_data=users_data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    相关资源
    最近更新 更多