file io - How do I create a incrementing filename in Python? -


i'm creating program create file , save directory filename sample.xml. once file saved when try run program again overwrites old file new 1 because have same file name. how increment file names whenever try run code again going increment file name. , not overwrite existing one. thinking of checking filename first on directory , if same code generate new filename:

fh = open("sample.xml", "w") rs = [blockresult] fh.writelines(rs) fh.close() 

i iterate through sample[int].xml example , grab next available name not used file or directory.

import os  = 0 while os.path.exists("sample%s.xml" % i):     += 1  fh = open("sample%s.xml" % i, "w") .... 

that should give sample0.xml initially, sample1.xml, etc.

note relative file notation default relates file directory/folder run code from. use absolute paths if necessary. use os.getcwd() read current dir , os.chdir(path_to_dir) set new current dir.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -