写入CSV时python添加了额外的空行

所以我和一个朋友正在用python开发游戏。但是,当我们获得写到排行榜的代码并存储为csv文件类型的外部文件时,似乎总是在输入之间添加空白行。

写入CSV时python添加了额外的空行

代码如下:

def leaderBoardWrite(winnerName,winnerScore):
    with open('leaderboard.csv',mode='a') as leaderboard:
        winnerScoreSort = "{:03d}".format(winnerScore)
        print(winnerScoreSort)
        leaderboardWrite = csv.writer(leaderboard,delimiter=',')
        leaderboardWrite.writerow([winnerScoreSort,winnerName]) ## This writes over the leaderboard,adding the newest score into it.
    leaderBoardRead()

有什么建议吗?

谢谢

编辑:由于某些人想要更广泛的代码规范,因此我将快速转发所有内容,以便您拥有完整的代码再现方法

## This is the start of the Dice game,look below at all of the comments to see what I have done once I have coded it.
## The next lines of code import all the nessasory modules for the program to run.
## The CSV Module is for the scoreboard
## Time is for the delays
## Random is for the
## Os is to clear the shell once the program has runself.
import csv,time,random,os
Complete = False ## Sets complete to false because the game has not begun
rounds = 0 ## Sets the rounds to 0 becasue game has not begun
playerOnescore = 000 ## Sets the player one score to 0 because they have not stated scoring yet
playerTwoScore = 000 ## Sets the player two score to 0 because they have not stated scoring yet
dice = [1,2,3,4,5,6] ## All the possible dice numbers
print("""
__          __  _                            _    _               _
\ \        / / | |                          | |  | |             | |
 \ \  /\  / /__| | ___ ___  _ __ ___   ___  | |  | |___  ___ _ __| |
  \ \/  \/ / _ \ |/ __/ _ \| '_ ` _ \ / _ \ | |  | / __|/ _ \ '__| |
   \  /\  /  __/ | (_| (_) | | | | | |  __/ | |__| \__ \  __/ |  |_|
    \/  \/ \___|_|\___\___/|_| |_| |_|\___|  \____/|___/\___|_|  (_) V.1.0.2
""")
time.sleep(1) ##Delay between welcome user and rules
print ("Welcome to my dice game! It is very simple to start playing.\nInput your username and password that were given to you and then type yes to verify you want to play (Please note 2 users both need to do this)\nBoth players will roll the dice twice\nThe totals of the rolls will be added to your net score\nIf your total is ODD,you will lose 5 points off of your overall score\nIf your total is EVEN,you will gain 10 points!\nIf you roll a double,the game will re-roll for you and you will gain the number of points rolled added to your score.\nThe winner is the person who has the most points at the end of the 5 rounds,once you have finished playing,you can see a leaderboard of players who have scored the most points.\nHave fun and good luck!")##Rules will be shown once at the start,straight after rules it will show the time delay.
print ("") ## Space between rules and dice delay
time.sleep(1) ## Delay between rules and dice delay
def PlayerOne(userOneName,playerOnescore,dice,delay): ## The function for Player One to start rolling and scoring
    input("[{}] When you are ready,press the ENTER key to roll the dice!".format(userOneName))
    diceoneRoll = dice[random.randint(0,len(dice)-1)] ## Rolls the first dice
    diceTwoRoll = dice[random.randint(0,len(dice)-1)] ## Rols the seccond dice
    total = diceoneRoll + diceTwoRoll ## Adds the scores from both dice rolls together
    if diceoneRoll == diceTwoRoll: ## Checks if both os the dice rolls were the same
        print("[{}] You have rolled a double,you get another roll!".format(userOneName))
        temp = PlayerOneReRoll(userOneName,dice) ## Calls a function to roll an extra die
        print("[{}] You scored {} from the reroll".format(userOneName,temp))
        playerOnescoreReturn = total + temp ## Adds the score of the reroll to their total score
    elif total % 2 == 0: ## Checks if the total of the two dice is even
        print("[{}] Your total was even,take an extra 10 points".format(userOneName))
        playerOnescoreReturn = total + 10
        pass
    elif total % 2 ==1: ## Checks if the total of the two dice is odd
        print("[{}] You have scored an odd number,you lose 5 points".format(userOneName))
        if playerOnescore-5 <0:
            playerOnescoreReturn = 0
        else:
            playerOnescoreReturn = -5

    else:
        pass
    time.sleep(delay)
    print("[{}] You scored {}".format(userOneName,total))
    time.sleep(delay)
    print("[{}] Your total score is {}".format(userOneName,playerOnescore+playerOnescoreReturn))
    return playerOnescoreReturn

def PlayerTwo(userTwoName,playerTwoScore,delay):
    input("\n[{}] When you are ready,press the ENTER key to roll the dice!".format(userTwoName))
    diceoneRoll = dice[random.randint(0,len(dice)-1)]
    diceTwoRoll = dice[random.randint(0,len(dice)-1)]
    total = diceoneRoll + diceTwoRoll
    if diceoneRoll == diceTwoRoll:
        print("[{}] You have rolled a double,you get another roll!".format(userTwoName))
        temp = PlayerTwoReRoll(userTwoName,dice)
        print("[{}] You scored {} from the reroll".format(userTwoName,temp))
        playerTwoScoreReturn = total + temp
    elif total % 2 == 0:
        print("[{}] Your total was even,take an extra 10 points".format(userTwoName))
        playerTwoScoreReturn = total + 10
        pass
    elif total % 2 ==1:
        print("[{}] You have scored an odd number,you lose 5 points".format(userTwoName))
        if playerTwoScore-5 <0:
            playerTwoScoreReturn = 0
        else:
            playerTwoScoreReturn = -5
    else:
        pass
    time.sleep(delay)
    print("[{}] You scored {}".format(userTwoName,total))
    time.sleep(delay)
    print("[{}] Your total score is {}".format(userTwoName,playerTwoScore+playerTwoScoreReturn))
    return playerTwoScoreReturn

def PlayerOneReRoll(userOneName,dice):
    input("[{}] Ready to roll the dice again? Press ENTER key to roll.".format(userOneName))
    diceoneRoll = dice[random.randint(0,len(dice)-1)]
    total = diceoneRoll
    return total

def PlayerTwoReRoll(userTwoName,dice):
    input("[{}] ".format(userTwoName))
    diceoneRoll = dice[random.randint(0,len(dice)-1)]
    total = diceoneRoll
    return total

def main(userOneName,userTwoName,rounds,Complete):
    print("\nRound [{}/5]\n".format(rounds))
    playerOnescoreTemp = PlayerOne(userOneName,delay)
    playerTwoScoreTemp = PlayerTwo(userTwoName,delay)
    return playerOnescoreTemp,playerTwoScoreTemp

def draw(userOneName,Complete):
    print("draw")
    playerOnescoreTemp = PlayerOneReRoll(userOneName,dice)
    playerTwoScoreTemp = PlayerTwoReRoll(userTwoName,dice)
    print("p1 = ",playerOnescoreTemp,"p2 = ",playerTwoScoreTemp)
    checkForWinner(userOneName,Complete,playerTwoScoreTemp)

def checkForWinner(userOneName,playerTwoScore):
    if Complete == True:
        if playerOnescore > playerTwoScore:
            print("\n[{}] You win with a score of {}. Well done".format(userOneName,playerOnescore))
            tmp = playerOnescore
            leaderBoardWrite(userOneName,tmp)
        elif playerTwoScore > playerOnescore:
            print("\n[{}] You win with a score of {}. Well done".format(userTwoName,playerTwoScore))
            tmp = playerTwoScore
            leaderBoardWrite(userTwoName,tmp)
        elif playerOnescore == playerTwoScore:
            print("\n[Both] It's come to a draw,play one last round to see who the ultimate champion is!" )
            draw(userOneName,Complete)
        else:
            pass
    else:
        pass

def leaderBoardWrite(winnerName,mode='a') as leaderboard:
        winnerScoreSort = "{:03d}".format(winnerScore)
        leaderboardWrite = csv.writer(leaderboard,adding the newest score into it.
    leaderBoardRead()

def leaderBoardRead():## Shows the ASCII text of "Leaderboard"
    print (""" 
 _      ______          _____  ______ _____  ____   ____          _____  _____  
| |    |  ____|   /\   |  __ \|  ____|  __ \|  _ \ / __ \   /\   |  __ \|  __ \ 
| |    | |__     /  \  | |  | | |__  | |__) | |_) | |  | | /  \  | |__) | |  | |
| |    |  __|   / /\ \ | |  | |  __| |  _  /|  _ <| |  | |/ /\ \ |  _  /| |  | |
| |____| |____ / ____ \| |__| | |____| | \ \| |_) | |__| / ____ \| | \ \| |__| |
|______|______/_/    \_\_____/|______|_|  \_\____/ \____/_/    \_\_|  \_\_____/
""")
    data = open('leaderboard.csv')
    for row in sorted(csv.reader(data)):
        print(row) ## This reads the leaderboard and allows it to be shown in the code

delay = int(input("Please input a time delay for the dice to roll?\n: "))

## User One Authorisation
with open("logins.csv",newline= '') as csvnames:
    authentication = csv.reader(csvnames,delimiter=",")
    logins = list(authentication)

while True:
    print("Welcome user one!")
    usernameInput = input("Please input your username? \n: ")
    userPasswordInput = input("Please input your password? \n: ")

    for i in range(len(logins)):
        if usernameInput == logins[i][0] and userPasswordInput == logins[i][1]:
            userOneName = logins[i][0]
            userOneAuthorised = True
            break
        else:
            userOneAuthorised = False

    if userOneAuthorised == False:
        print("Sorry {},you aren't authorised so run this task! \nPlease contact your System Administrator".format(usernameInput))
    else:
        try:
            ready = input("Welcome {},you have been Authorised. Are you ready to play? (Please type **yes** or **no**) \n:_ ".format(userOneName))
            if ready[0].lower() == "y":
                userOneAuthorised = True
                break
            else:
                print("Please come back later,the game will be waiting for you!")
        except:
            pass

## User Two Authorisation
while True:
    print("Welcome user 2!")
    usernameInput = input("What is your username? \n: ")
    userPasswordInput = input("What is your password? \n: ")

    for i in range(len(logins)):
        if usernameInput == logins[i][0] and userPasswordInput == logins[i][1]:
            userTwoName = logins[i][0]
            userTwoAuthorised = True
            break
        else:
            userTwoAuthorised = False

    if userTwoAuthorised == False:
        print("Sorry {},you aren't authorised so run this task! \nPlease contact your System Administrator".format(usernameInput))
    else:
        ready = input("Welcome {},you have been Authorised. Are you ready to play? (Please type **yes** or **no**) \n:_ ".format(userTwoName))
        try:
            if ready[0].lower() == "y":
                userTwoAuthorised = True
                break
            else:
                print("Please come back later,the game will be waiting for you!")
        except:
            pass



if userOneAuthorised == True and userTwoAuthorised == True:
    print("Starting")
    for i in range(1,6):
        roundNums = main(userOneName,i,Complete)
        playerOnescore+=roundNums[0]
        playerTwoScore+=roundNums[1]
        if i == 5:
            Complete = True
        else:
            pass
        checkForWinner(userOneName,playerTwoScore)
else:
    pass

time.sleep(4)

对不起,这样的顺序太尴尬了,我的朋友似乎喜欢点点有趣的东西。 感谢您到目前为止的所有建议。

qq872167458 回答:写入CSV时python添加了额外的空行

我以前有同样的问题。我最后写了一个宏来删除空白行。我建议将每行所需的所有详细信息放入地图中,将地图附加到列表中,然后使用熊猫将地图列表转换为数据框。然后使用df.to_csv(filename)函数将其粘贴到电子表格中。

如果您需要不断追加到电子表格中,那么您要做的就是使用pandas.read_csv(filename)读取csv,在上面创建数据框,追加到当前的数据框中,然后使用to_csv。您唯一需要确保的是to_csv在打印时添加索引列,因此请确保在添加数据前将数据框缩小为仅所需的列。它不会破坏任何内容,但是会使电子表格中存储的数据有点混乱。

祝你好运!

本文链接:https://www.f2er.com/2925273.html

大家都在问