【发布时间】:2016-05-03 01:54:37
【问题描述】:
我正在尝试在 python 3.5.1 中为基于文本的游戏编写一个保存/加载函数,我在这个站点上找到了一些有用的代码,不幸的是,这两个函数只需要一个文件路径作为参数之一。我正在学习python,并且对该站点和一般编码都相对较新,因此将不胜感激有关如何输入有效文件路径(以及在这种情况下有效文件路径的示例!)的帮助(再一次,我就像 Jon Snow)。相关方法贴在下面:
def __init__(self, name):
self.name = name
self.maxHealth = 100
self.health = self.maxHealth
self.baseAttack = 10
self.credits = 10
self.augs = 0
self.weap = ["Basic Nanite Pack"]
self.currWeap = ["Basic Nanite Pack"]
global playerFile
playerFile = {"name":self.name, "health":self.maxHealth, "maxHealth":self.health, "baseAttack":self.baseAttack,
"weapon":self.weap, "currWeap":self.currWeap, "credits":self.credits, "augs":self.augs}
def saveGame(playerFile, filepath):
with open(filepath, 'w') as outfile:
for name,num in playerFile.items():
outfile.write("{};{};\n".format(num, name))
import csv
def loadGame(filepath):
with open(filepath) as infile:
# purposeful misspell for variable name
playerFil = dict((v,k) for v,k,_ in csv.reader(infile, delimiter=';'))
return playerFil
【问题讨论】: