简体   繁体   中英

save json file within a loop, python

in jupyter notebook, I ran this code in a cell:

for i in range(10):
  with open('data.json', 'w') as f:
    json.dump({"counter":i}, f)
  time.sleep(10000)

easy so far, but after executing the cell there won't be any update on the actual data.json file during each iteration, it will get updated up until the end of the program. in other words, the data.json as a file object stays open till the end of the code.

how can I update the file on the disk in a loop?

The json module doesn't work that way AFAIK. You'll have to load the json data into a dictionary/list then make your changes, then write the file again:

# funciton to read json files
def read_json(path):
    with open(path, 'r') as file:
        return json.load(file)

# function to write json files
def write_json(path, data, indent=4):
    with open(path, 'w') as file: 
        json.dump(data, file, indent=indent) 

# read some json data
json_data = read_json('./my_json_file.json')

# ... do some stuff to the data

# write the data back to the file
write_json('./my_json_file.json', json_data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM