有没有办法在文本周围插入大括号,使其成为字符串格式的词典?

2024-10-01 09:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的python程序中,我有一个添加到文本文件的键和值的列表,我需要能够提取这个字符串列表并将其转换为字典。你知道吗

例如:

    counter = 0
    add = str(counter)
    counterDict = UserID + ": " + add + ", "
    counter = counter + 1

#This should make counterDict look like: ""Smi39119": 0, "Joh38719": 1, " etc.

    f = open("Dictionaries.txt","a")
    f.write(counterDict)
    f.close()

#Then I would like to be able to open the file and turn that string into a dictionary

    f = open("Dictionaries.txt","r")
    string = f.read()

#This way 'string' should still be a string, but look like this: "{"Smi39119": 0, "Joh38719": 1, }"

我不知道这是否可行,但如果可行,我们将非常感谢所有的解决方案。你知道吗


Tags: totxtadd列表stringcounteropenthis
1条回答
网友
1楼 · 发布于 2024-10-01 09:25:48

我猜您正在尝试将字典保存到一个文件中,*输入*:json文件系统, 你不需要把字典转换成字符串,让json帮你把它转换成字符串。你知道吗

import json

f = open("Dictionaries.json","a")
f.write(json.dumps(your_dictionary))
f.close()

# load it and use it like a dictionary

f = open("Dictionaries.json","r")
your_dictionary = json.loads(f.read())

同时读取Writing a dict to txt file and reading it back?

干杯!你知道吗

相关问题 更多 >