How can I "build" a dictionary within a txt file using Python, over time?
I need to take two variables, for example...
some_string = "Hello, World!"
some_float = 3958.8
...then write those two variables to a txt file, as a dictionary.
For the key/value pair, some_string should be the key, and some_float should be the value.
Next time I run the program, some_string and some_float will be different, and will need to get written/added to the same txt file, essentially adding another key/value pair to the now already existing dictionary (txt file).
All I've been able to find is information regarding adding a known dictionary to a txt file, not building one up over time. In my case, I don't know ahead of time what some_string and some_float will be next time I run the program, so I can't pre-build the dictionary and just write it all to the txt file at once.
Any ideas?
CodePudding user response:
You can use open file mode append ('a') to append to the file the new content and update the file that way every time you add a new value. Here's an exemple on how to do it:
def add_dic(key, value):
with open('dic.txt', mode='a') as fp:
fp.write(key " " str(value) '\n')
def read_dic():
dic = {}
with open('dic.txt', mode='r') as fp:
for line in fp.readlines():
words = line.split(' ')
key = words[0]
value = float(words[1])
dic[key] = value
return dic
some_string = input("string: ")
some_float = float(input("float: "))
add_dic(some_string, some_float)
dic = read_dic()
print(dic)
CodePudding user response:
I am not quite sure whether this what you are looking for but you can use the method explained in this https://link.medium.com/3v2WRRxFYqb it shows how to update the existing lines or create new ones.