Reputation: 672
Hello I am making a game out of python, and I made the game write data on a text document, and is there a way I can code so if the text file says a person named Bob is on level 4, then make the program start on level 4. I have tried using for loop to do the job, but it wont work. It will not initiate the text file and just goes over to level 1. Here is the game code(for reading and writing:
import os
#---------------------------
os.system("color a")
#---------------------------
def ping(num):
os.system("ping localhost -i", num, ">nul")
def cls():
os.system("cls")
#--------------------------
print("the game")
ping(2)
cls()
print("1: New Game")
print("2: Continue")
print("3: Credits")
while True:
choice=input("Enter")
if choice==1:
name=input("Enter your name")
firstsave=open("data.txt", "W")
firstsave.write(name, " ")
# there will be the game data here
elif choice==2:
opendata=file("data")
#opening the file
while True:
''' is the place where the file scanning part needs to come.
after that, using if and elif to decide which level to start from.(there are a total of 15 levels in the game)
'''
The text file:
User Level
Bob 5
George 12
Upvotes: 0
Views: 390
Reputation: 437
You haven't given quite enough information, but here's one approach:
elif choice == 2:
with open("x.txt") as f:
f.readline() # skip the first line
for lines in f: # loop through the rest of the lines
name, level = line.split() # split each line into two variables
if name == playername: # assumes your player has entered their name
playlevel(int(level)) # alternatively: setlevel = level or something
break # assumes you don't need to read more lines
This assumes several things, like that you know the player name, and that the player has only one line, the name is just a single word, etc. Gets more complicated if things are different, but that's what reading the Python documentation and experimenting is for.
Also note that you use 'w' to write in choice 1, which will (over)write rather than append. Not sure if you meant it, but you also use different filenames for choice 1 and 2.
Upvotes: 1