1

i have a file that looks like so: {"Apples": 14, "Bananas": 14, "Pineapples": 0, "Pears": 8}

im trying to figure out how i can read this file in and be able to use it so that i can for example reduce the "apples" value to lower i.e 13 from 14

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149

1 Answers1

0

Assuming its just a text file:

You can just read the file and create a dictionary using literal_eval()

from ast import literal_eval
with open("file.txt") as f:
    a = f.read()
    dic= literal_eval(a)

At this point you can just modify anything in the dict:

dic["apples"] = 13

To write it back to file you can just convert it back to a string and write:

w = str(dic)

with open("file.txt", "w+") as f:
    f.write(w)
Primusa
  • 13,136
  • 3
  • 33
  • 53