+ 2
Save Dictionary values to a file?
I'm very new, but is there a way to save Dictionary values to a file? I don't want the file to be rewritten, just added on to. I thought about converting the values into strings but I'm not sure how to do that... Here's an example of what I've got dict = {} dict[1] = 'a'; dict[2] = 'b'; dict[3] = 'c'; f = (r"letter.txt") f.open(r"letter.txt", "a") f.write(str(dict[3])) f.close I get an error, but is there a better way to do this?
4 Antworten
+ 5
With pickle module, you can save data types directly. (Pickle does the necessary steps for you.)
The whole object with its contents will be stored and recreated when you load it later.
+ 5
Dictionaries cannot be directly encoded into a file. You probably have to do string manipulation.
Therefore, you need to format your data. For example, you store each entry as:
{key}: {value}
Then,
with open("text.txt", "w") as file:
for i in dict:
file.write(f"{i}: {dict[i]}")
+ 2
Are you getting an error on a computer or sololearn code playground?