当我完成我制作的游戏时,我制作了一个保存按钮,保存到文件中。当游戏打开时,它将读取文件并将这些行保存为变量。我这样做,但后来我发现它需要是一个整数,所以我使用Query executed successfully: Pragma table_info(jobs); (took 1ms)
cid name type pk
2 age text 0 //rows title and job_id have been ignored as they are as expected
。但是它不起作用,因为变量是int()
而不是"0\n"
。我检查了很多其他问题,但是他们没有问或回答同样的问题。
所以我想知道,有没有办法"0"
最后没有readlines()
?或者有没有办法可以自动退格变量?这是我的代码:
\n
如果没有答案,我很乐意评论或回答。
答案 0 :(得分:3)
首先,您的代码存在逻辑错误。
if savedlines == []:
eggz = 0
eggvalue = 0.2
chookz = 0
eggzps = 0.0
eggvalueupgrade = 100
money = eggz * eggvalue
eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])
您检查whe savedlines
是否为空列表并相应地设置一些值。但是,如果这是真的,由于您的列表为空,以下行将因IndexError
而失败。您需要将其更改为:
if savedlines == []:
eggz = 0
eggvalue = 0.2
chookz = 0
eggzps = 0.0
eggvalueupgrade = 100
money = eggz * eggvalue
else:
eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])
现在,要解决这个问题。行之后:
savedlines = savedfile.readlines()
你应该添加以下行,它将从行的末尾删除\n
:
savedlines = [line.rstrip("\n") for line in savedlines]
答案 1 :(得分:1)
In [17]: fff = open('/somefile', 'r')
In [18]: ss = fff.readlines()
In [19]: ss
Out[19]: ['qqq\n', 'www\n', 'aaa\n']
In [20]: ss = [ww.strip('\n') for ww in ss]
In [21]: ss
Out[21]: ['qqq', 'www', 'aaa']