我正在为缺少它的游戏编写锦标赛创建器,仅供个人使用。这对学校来说是一个很好的练习……但是,我在完成该程序时偶然发现了一个问题。
所以在比赛的参赛者确定之后,我问用户(我自己,最多我表弟也过来,如果他过来的话)是否要保存当前的参赛者名单。如果是这样,包含参与者的列表将写入文件:
fileWrite = open('Previous Participants', 'w')
fileWrite.write(str(participants2))
fileWrite.close()
但是,这会将列表转换为字符串,所以如果我想在下次程序运行时读出它……我有一个字符串。不是列表,我需要锦标赛创建者本身的列表(随机化战斗等)。
那么...我如何将这个字符串作为列表返回?问题是,我认为我可以使用 split,但我相信参与者名称中包含空格会成为问题。
当前文件中有上次的这个字符串:
['Cell', 'Lord Slug', 'Time Patroller', 'Gotenks', 'Omega Shenron', 'Nail', 'Time Breaker Bardock', 'Piccolo', 'Frieza', 'Mr. Satan', 'Beerus', 'Nappa', 'Raspberry', 'Goten', 'Vegito', 'Goku']
如果我这样做,像“Lord slug”这样的参与者会引起问题:
ownCharacters = input('Do you wish to use the same participants as last time? ')
if ownCharacters == 'yes' or ownCharacters == 'Yes':
try:
fileRead = open('Previous Participants', 'r')
participants2 = fileRead.read()
participants2.split
except FileNotFoundError:
participants2 = participants2
他们不会吗? 顺便说一句,当程序到达这一点时,participants2 已经填充了随机名称,因此如果文件不存在,它应该继续使用随机名称。
请您参考如下方法:
一个更好的方法是将名称每行写入一个文件:
fileWrite.write('\n'.join(participants2))
然后您可以通过readlines 检索名称列表:
participants2 = fileRead.readlines() # elements will will need to be stripped
但是,将数据序列化到文件的正确方法是使用经过测试的库,如 pickle或 json :
import json
# import pickle
with open('file.json', 'w') as f:
json.dump(participants, f)
# pickle.dump(participants, f)
然后您可以通过以下方式检索列表:
with open('file.json', 'r') as f:
participants = json.load(f)
# participants = pickle.load(f)
