On 06/06/2013 06:50 AM, Avnesh Shakya wrote:
I am running a python script and it will create a file name like filename0.0.0 and If I run it again then new file will create one more like filename0.0.1...... my code is-
i = 0
Redundant initialization of i.
for i in range(1000):
with open('filename%d.%d.%d.json'%(0,0,i,)): pass
dataFile = file('filename%d.%d.%d.json'%(0,0,i,), 'a+')
But It will take more time after creating many files, So i want to store value of last var "i" in a variable
There are no variables once the program ends. You mean you want to
store it in the file. That's known as persistent storage, and in the
general case you could use pickle or something like that. But in your
simple case, the easiest thing would be to simply write the last value
of i out to a file in the same directory.
Then when your program starts, it opens that extra file and reads in the
value of i. And uses that for the starting value in the loop.
so that when i run my script again then I can use it. for example-
my last created file is filename0.0.27 then it should store 27 in a variable and when i run again then new file should be created 0.0.28 according to last value "27", so that i could save time and it can create file fast..
Please give me suggestion for it.. How is it possible?
Incidentally, instead of opening each one, why not check its existence?
Should be quicker, and definitely clearer.
Entirely separate suggestion, since I dislike having extra housekeeping
files that aren't logically necessary, and that might become out of synch :
If you're planning on having the files densely populated (meaning no
gaps in the numbering), then you could use a binary search to find the
last one. Standard algorithm would converge with 10 existence checks if
you have a limit of 1000 files.