几天前我开始研究我的游戏。我制作了加载(启动时)和保存(退出时)的系统。在第一次登录时,一切都很好,但是出现了第二个错误(NameError:名称'奇怪的'未定义)。有人可以帮我解决吗?我知道问题在于找到文件中的名称因为我试图在
之后的所有内容之后放置其他语句elif ab.read().find(a) != -1:
并且我放在其他地方的工作但是它只是打印所以其他所需的并没有在其他地方工作。 这是我的计划:
import sys, random, time, re
print("Welcome to game Special Travel Adventure!")
def con(a, b):
return a.lower() == b.lower()
a = str(input("If you want to continue with game type your name here: "))
ab = open("STAPlayers.txt", "r+")
if ab.read().find(a) == -1:
if ab.read() == "":
ac = "Name:" + a + ":Strange:" + "0" + ":Courage:" + "0" + ":Skills:" + "0" + ":Money:" + "0" + ":Level:" + "0" + ":Deaths:" + "0"
ab.write(ac)
strange = 0
courage = 0
skills = 0
money = 0
level = 0
deaths = 0
else:
ac = "\nName:" + a + ":Strange:" + "0" + ":Courage:" + "0" + ":Skills:" + "0" + ":Money:" + "0" + ":Level:" + "0" + ":Deaths:" + "0"
ab.write(ac)
strange = 0
courage = 0
skills = 0
money = 0
level = 0
deaths = 0
elif ab.read().find(a) != -1:
readdd = ab.readlines()
for line in readdd:
if line.find(a) != -1:
zm = line.split(":")
zm.remove("Name")
zm.remove("Strange")
zm.remove("Courage")
zm.remove("Skills")
zm.remove("Money")
zm.remove("Level")
zm.remove("Deaths")
strange = int(zm[1])
courage = int(zm[2])
skills = int(zm[3])
money = int(zm[4])
level = int(zm[5])
deaths = int(zm[6])
ab.close()
def levelc():
if courage and strange and skills == 1:
level += 1
return True
if courage and strange and skills == 2:
level += 1
return True
if courage and strange and skills == 3:
level += 1
return True
if courage and strange and skills == 4:
level += 1
return True
if courage and strange and skills == 5:
level += 1
return True
else:
return False
b = input("Start Menu\nSelect: Start, Upgrades, Exit. ")
while b != "dont save":
if con(b, "Exit"):
aj = open("STAPlayers.txt", "r")
lines = aj.readlines()
aj.close()
aj = open("STAPlayers.txt", "w")
jmj = "Name:" + a + ":Strange:" + str(strange) + ":Courage:" + str(courage) + ":Skills:" + str(skills) + ":Money:" + str(money) + ":Level:" + str(level) + ":Deaths:" + str(deaths)
for linee in lines:
if str(a) not in linee:
aj.write(linee)
elif str(a) in linee:
jmjm = jmj + "\n"
aj.write(jmjm)
aj.close()
sys.exit()
break
我知道问题在于找到文件中的名字因为我试图在
之后的所有内容中放置其他语句elif ab.read().find(a) != -1:
并且我放在其他地方的工作但是它只是打印所以其他所需的并没有在其他地方工作。请帮忙。
答案 0 :(得分:3)
您的问题是您尝试两次读取文件。您只能读取一次文件(不重置到文件的开头)。试试这个:
ab_read = ab.read()
if ab_read.find(a) == -1:
...
elif ab_read.find(a) != -1:
...
尽管如此,您最好使用if a in ab_read:
,然后使用else
。此外,您可能会考虑比ab
或a
更有意义的变量名称。
要回答您将遇到的下一个问题:您对readdd = ab.readlines()
的调用将因同一次ab.read()
次调用失败而失败。您可以使用readdd = ab_read.splitlines()
通常,您经常阅读 way 文件。从任何语言中读取文件是一项缓慢且耗费资源的操作。您可以考虑在非常糟糕的编程习惯中多次读取同一文件。您应该重构代码以仅读取每个文件一次,这应该可以解决您的大部分问题。