我有一个文本文件,我读取的信息作为变量,作为我的游戏保存系统。问题是我需要我的文档读写到某一行,它在第一次读写时工作正常,但是第二次行在它上移一行之前,我得到“索引超出范围”,因为我试图写/读的行是空的。你知道吗
我看了我的代码,似乎找不到问题。。你知道吗
gold=(60)
goldtxt=(str(gold) + 'gp')
inventory=['empty','empty','empty','empty','empty','empty','empty','empty','empty','empty',]
def ItemAdd(event):
gamestatus = linecache.getline('C:Location', 2).rstrip()
if gamestatus == 'gamestatus1':
gameinfo1[7] = (inventory[(-1)]).strip('empty') + ' '
gameinfo1[9] = goldtxt + ' '
with open('C:Location', 'w') as active:
active.writelines(gameinfo1)
RefreshTexts()
def RefreshTexts():
with open('C:Location', 'r') as file:
datatemplate = file.readlines()
with open('C:Location', 'r') as file:
gameinfo1 = file.readlines()
with open('C:Location', 'r') as file:
gameinfo2 = file.readlines()
with open('C:Location', 'r') as file:
gameinfo3 = file.readlines()
with open('C:Location', 'r') as file:
activeinfo = file.readlines()
我有一千多行,但我认为这就是问题所在,如果有一行的话。你知道吗
我认为出现错误的原因可能是因为您使用的是
rstrip
在某些地方去掉了行末尾的换行符;也可能是因为您使用的是linecache
;尽管Python 2文档中提到了一般的行随机访问,但在Python 3中,文档清楚地指出:在任何情况下,使用} 和^{} 将游戏状态数据保存并加载到单个字典中
linecache
都不适合您的用例,因为linecache
假定文件没有更改,但是您的保存文件确实更改了;并且您在保存之后正在刷新它们。我建议您使用^{比如:
运行程序打印
而
mysavegame
的内容是相关问题 更多 >
编程相关推荐