从python中的文件中检索字符串并更改元组

时间:2021-10-14 05:51:55

I have a serious snag in my programming, and it might be an easy fix, but anytime I find something that looks like the right forum post, it's not quite right.

我的编程有一个严重的障碍,这可能是一个简单的修复,但任何时候我发现一些看起来像正确的论坛帖子,它是不对的。

I'm using a file to store data created from one part of my program, like a high score, number of times played, and player name.

我正在使用一个文件存储从我的程序的一部分创建的数据,如高分,播放次数和玩家名称。

I store all this data just fine in the file with a tuple set of ("string key", key's value). I like the ease of retrieval with the dict() command, and have worked with both, but I have to convert the entire data set into a string in order to store it to the file.

我用文件集(“字符串键”,键的值)将所有这些数据存储在文件中。我喜欢使用dict()命令检索的简易性,并且使用了两者,但我必须将整个数据集转换为字符串,以便将其存储到文件中。

And

When I retrieve the data for the next time I open the program, I can't seem to add to the "number of times played" or change the players name for the high score..

当我下次打开程序时检索数据时,我似乎无法添加“播放次数”或更改高分的玩家名称。

It looks a little like this:

看起来有点像这样:

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()

Can anyone give me any direction add to what I should look into.. I'm on my phone and can't give proper code examples right now...

任何人都可以给我任何方向添加到我应该看到的内容..我在手机上,现在无法给出正确的代码示例...

1 个解决方案

#1


Have you considered using an actual serializing library? For example json is very useful. Particularly if you're just dumping a dict.

您是否考虑过使用实际的序列化库?例如,json非常有用。特别是如果你只是倾销一个字典。

For example:

>>> d = {'level':2, 'position':[2,3]}
>>> import json
>>> json.dumps(d) # or json.dump(d, save) in your code
'{"position": [2, 3], "level": 2}'

That way you could simply load the string using json.loads. Or directly a file using json.load.

这样你就可以使用json.loads加载字符串。或直接使用json.load的文件。

#1


Have you considered using an actual serializing library? For example json is very useful. Particularly if you're just dumping a dict.

您是否考虑过使用实际的序列化库?例如,json非常有用。特别是如果你只是倾销一个字典。

For example:

>>> d = {'level':2, 'position':[2,3]}
>>> import json
>>> json.dumps(d) # or json.dump(d, save) in your code
'{"position": [2, 3], "level": 2}'

That way you could simply load the string using json.loads. Or directly a file using json.load.

这样你就可以使用json.loads加载字符串。或直接使用json.load的文件。