从 python 中的文件中检索字符串并更改元组
retrieving string from file in python and changing tuples
我的编程遇到了严重的障碍,这可能很容易解决,但每当我发现一些看起来像正确论坛的东西时 post,它并不完全正确。
我正在使用一个文件来存储从我的程序的一部分创建的数据,例如高分、播放次数和玩家姓名。
我将所有这些数据都很好地存储在一个元组集("string key",键的值)的文件中。我喜欢使用 dict() 命令轻松检索,并且两者都使用过,
但
我必须将整个数据集转换为字符串才能将其存储到文件中。
和
当我下次打开程序检索数据时,我似乎无法添加到 "number of times played" 或更改高分球员的名字..
看起来有点像这样:
import sys
import random
import pickle
save=open ("(path to file)/newgame.txt", 'r+')
save.seek(0)
hiscore=(save.readlines())
def Savedata():
global save
global name
global highscore
global numplays
#this is where the ideal code would split, modify, and repack the data from the file
save.seek(0)
save.write(str (hiscore))
print (save)
save.seek(0)
save.close()
任何人都可以给我任何方向,添加到我应该研究的内容中。我正在 phone,现在无法提供正确的代码示例...
您是否考虑过使用实际的序列化库?例如 json
非常有用。特别是如果你只是转储字典。
例如:
>>> d = {'level':2, 'position':[2,3]}
>>> import json
>>> json.dumps(d) # or json.dump(d, save) in your code
'{"position": [2, 3], "level": 2}'
这样您就可以使用 json.loads
简单地加载字符串。或者直接使用 json.load
.
的文件
我的编程遇到了严重的障碍,这可能很容易解决,但每当我发现一些看起来像正确论坛的东西时 post,它并不完全正确。
我正在使用一个文件来存储从我的程序的一部分创建的数据,例如高分、播放次数和玩家姓名。
我将所有这些数据都很好地存储在一个元组集("string key",键的值)的文件中。我喜欢使用 dict() 命令轻松检索,并且两者都使用过, 但 我必须将整个数据集转换为字符串才能将其存储到文件中。
和
当我下次打开程序检索数据时,我似乎无法添加到 "number of times played" 或更改高分球员的名字..
看起来有点像这样:
import sys
import random
import pickle
save=open ("(path to file)/newgame.txt", 'r+')
save.seek(0)
hiscore=(save.readlines())
def Savedata():
global save
global name
global highscore
global numplays
#this is where the ideal code would split, modify, and repack the data from the file
save.seek(0)
save.write(str (hiscore))
print (save)
save.seek(0)
save.close()
任何人都可以给我任何方向,添加到我应该研究的内容中。我正在 phone,现在无法提供正确的代码示例...
您是否考虑过使用实际的序列化库?例如 json
非常有用。特别是如果你只是转储字典。
例如:
>>> d = {'level':2, 'position':[2,3]}
>>> import json
>>> json.dumps(d) # or json.dump(d, save) in your code
'{"position": [2, 3], "level": 2}'
这样您就可以使用 json.loads
简单地加载字符串。或者直接使用 json.load
.