简体   繁体   中英

How do I save the dictionary with new name every time when my code runs?

I am trying to save the dictionary with new name , every time whenever my code runs .

Code :

   import json
   dictionary = {'happy':1,'sad':2,'angry':3}
   count = 0
   with open('/home/hamza/Desktop/time_duration_file'+str(count)+'.json','w') as data:
   file = json.dump(dictionary,data)
   count+=1

Above code is overwriting the dictionary whenever my code runs . I want to save the dictionary every time with a new name ,whenever my code runs.

Expected output:

Code Runs (1)
Code Runs (2)
     .
     .

Ouput should be:

 time_duration_file1.json
 time_duration_file2.json
         .
         .

Well, you're not doing anything to actually count the number of files already created; you're just setting count to zero.

Try something like

import glob

count = len(glob.glob('/home/hamza/Desktop/time_duration_file*.json'))

# ...

You can use time for doing this. Try this:

import json
import time

dictionary = {'happy':1,'sad':2,'angry':3}

with open('/home/hamza/Desktop/time_duration_file'+str(time.time())+'.json','w') as data:
        file = json.dump(dictionary,data)

You can try this :

import random

with open('/home/hamza/Desktop/time_duration_file'+str(random.randint(1, 10000))+'.json','w') as data:
    file = json.dump(dictionary,data)

This will create a completely different file name everytime you run your script.

And if you want to save continuous you can try this :

import os 

with open('/home/hamza/Desktop/time_duration_file'+str(len(os.listdir("/home/hamza/Desktop")))+'.json','w') as data:
    file = json.dump(dictionary,data)

Your issue is that the value stored in count is not going to be preserved. In other words, each time your code runs, the value of count is reset to 0. As Daniel has mentioned, you could solve this by counting the number of json files already in the directory and then adding one.

This would look something like:

import glob
import json

count = len(glob.glob('time_duration_file*.json'))
dictionary = {'happy':1,'sad':2,'angry':3}
with open('time_duration_file'+str(count+1)+'.json','w') as data:
   file = json.dump(dictionary,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