从.tx创建变量和字典

2024-09-27 09:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有这个作为我的代码

def makeFolder():
    if not os.path.exists('Game Saves'): os.makedirs('Game Saves')
def saveAllPlayerInfo(dest,fileName):
    f=open(dest+fileName,'w')
    f.write("{0}:{1}\n".format('playerName',playerName))
    f.write("playerStats={\n")
        f.write("\t'{0}':'{1}'\n".format('playerMaxHp',playerStats['playerMaxHp']))
    f.write("\t'{0}':'{1}'\n".format('playerCurrentHp',playerStats['playerCurrentHp']))
    f.write("\t'{0}':'{1}'\n".format('playerAtk',playerStats['playerAtk']))
    f.write("\t'{0}':'{1}'\n".format('playerDef',playerStats['playerDef']))
    f.write("\t'{0}':'{1}'\n".format('playerDefending',playerStats['playerDefending']))
    f.write("\t'{0}':'{1}'\n".format('playerRunAbility',playerStats['playerRunAbility']))
    f.write("\t'{0}':'{1}'\n".format('luck',playerStats['luck']))
    f.write("\t'{0}':'{1}'\n".format('playerExperience',playerStats['playerExperience']))
    f.write("\t'{0}':'{1}'\n".format('level',playerStats['level']))
    f.write("\t}")
    f.close()

def saveFile():
    makeFolder()
    dest=os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'\\Game Saves\\'
    fileName="{0}.txt".format(playerName)
    if not (os.path.isfile(dest+fileName)):
            print("New File Created")
            print("Game Has Been Saved")
            saveAllPlayerInfo(dest,fileName) 
    elif (os.path.isfile(dest+fileName)):
            saveAllPlayerInfo(dest,fileName)
            print("Game Has Been Saved")

def readFile():
    gameFiles=[f for f in os.listdir(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'\\Game Saves\\') if isfile(join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'\\Game Saves\\',f))]
    dest=os.path.basename(os.path.abspath(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'\\Game Saves\\'))
    print("What would you like to do?")
    print("1. Load a Game")
    print("2. Start a New Game")
    ans=input()
    a=0
    while a==0:
            if ans.lower() in ["1.","1","load a game","load game","load"]:
                    print("")
                    print("Select Which Game: ")
                    filesRead=0
                    for saves in gameFiles:
                            gameSave=(open(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'\\Game Saves\\'+gameFiles[filesRead],'r'))
                            firstLine=gameSave.readline()
                            print("{0}. {1}".format(filesRead+1, firstLine[11:]))
                            filesRead+=1
                    gameToLoad=input("")
                    if int(gameToLoad)<=filesRead:
                            exec(gameSave.read())                  
                    a=1
            elif ans.lower() in ["2.","2","start a new game","start a game","start game","start"]:
                    clr()
                    newGame()
                    a=1
            else:
                    print("I didn't understand that. Can you say that again?")

这是从中提取的文件。它被称为“Alex.txt”

playerName:Alex
playerStats={
'playerMaxHp':'10'
'playerCurrentHp':'10'
'playerAtk':'5'
'playerDef':'5'
'playerDefending':'0'
'playerRunAbility':'10'
'luck':'10'
'playerExperience':'0'
'level':'1'
}

现在,我明白了,它目前无论如何都不需要将您输入的文件转换为程序应该加载的代码。但这不是我担心的。 这里的问题是,我想要一个尽可能优雅和简单的解决方案来加载文件。这就是为什么我把它保存在我做的格式。这就是代码本身的确切格式。 但当我按原样执行时

Traceback (most recent call last):
  File "E:\Game.py", line 614, in <module>
readFile()
  File "E:\Game.py", line 82, in readFile
exec(gameSave.read())
  File "<string>", line 3
'playerCurrentHp':'10'
                 ^
SyntaxError: invalid syntax

当我做eval()时,我得到了

Traceback (most recent call last):
  File "E:\Game.py", line 614, in <module>
readFile()
  File "E:\Game.py", line 82, in readFile
eval(gameSave.read())
  File "<string>", line 1
playerStats={
           ^
SyntaxError: invalid syntax

两者都有问题。如果可能的话,我想要几行代码。 我也尝试过让它一行一行地运行,但是两者都不接受eval被卡住的行(意外的EOF错误)。 我不会导入任何第三方模块。我在许多计算机上工作,我不想在我为一个项目工作的所有计算机上安装模块

有人能为我的问题提供一个优雅的解决方案吗? (还有,有没有办法简化我的读取函数,特别是dest=part?我觉得很复杂。我只是在这里搜索,做了一些测试,把一些东西放在一起,直到成功,然后坚持下来。但感觉它应该可以不那么迟钝。)


Tags: pathingameformatoslinefilenamefile

热门问题