简体   繁体   中英

How to read a variable from a text file as an integer, modify said variable then store it in the same text file in Python?

Beginner programmer here, so be weary of that. I'm currently working on a text-based turn-based battle "simulator" in Python. I want to add to my code a way to store and read the number of wins and losses the player has so that they can see these stats in the menu. The turn-based part functions as intended, however the wins/losses stats (which I'm going to call "score" for the remaining explanation) do not. I have a text file named "wl.txt" with the score stored inside. It is two simple lines with the numbers of corresponding wins and losses, wins being on the first line and losses being on the second. As I want to update the score as the player advances, the two variables need to be integers for them to be updated accordingly. To retrieve them from "wl.txt", I used the readline() method for wins and readlines() method for losses. However, as you probably know, readline() returns a str and readlines() returns a list, so I cannot update the value of the losses variable. Here is a python file regrouping the code I use for this:

def SeeScore():
    score = open("wl.txt", "r")
    print("Wins:",score.readline(), "\nLosses:", score.readlines())


score = open("wl.txt", "r")
wins = score.readline()
losses = score.readlines()
score.close()

wins += 2
losses += 5
score = open("wl.txt", "w")
score.write(str(wins)+"\n")
score.write(str(losses)+"\n")

SeeScore()

I have tried to do something like this:

wins = int(score.readline())
losses = int(score.readlines())

But you also probably know that you cannot turn a list into an integer.

I'm at a loss for what to do.

Thanks in advance.

For the losses you were using score.readlines which made it print ['1'] instead of just 1. Another issue is that you need to put int().

After testing with your code simply just replace

"\nLosses:", score.readlines())
# And
wins = score.readline()
losses = score.readlines()

With

"\nLosses:", score.readline())
# And
wins = int(score.readline())
losses = int(score.readline())

Final code:

def SeeScore(wins, losses):
    print("Wins:",wins, "\nLosses:", losses)


score = open("wl.txt", "r")
wins = int(score.readline())
losses = int(score.readline())
score.close()



wins += 2
losses += 5
score = open("wl.txt", "w")
score.write(str(wins)+"\n")
score.write(str(losses)+"\n")

SeeScore(wins, losses)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM