Save to a file, but avoid overwriting an existing file

zoom zoom at yahoo.com
Wed Mar 12 13:29:49 CET 2014


Hi!

I would like to assure that when writing to a file I do not overwrite an 
existing file, but I'm unsure which is the best way to approach to this 
problem. As I can see, there are at least two possibilities:

1. I could use fd = os.open("x", os.O_WRONLY | os.O_CREAT | os.O_EXCL)
which will fail - if the file exists. However, I would prefer if the 
program would try to save under different name in this case, instead of 
discarding all the calculation done until now - but I' not too well with 
catching exceptions.

2. Alternatively, a unique string could be generated to assure that no 
same file exists. I can see one approach to this is to include date and 
time in the file name. But this seems to me a bit clumsy, and is not 
unique, i.e. it could happen (at least in theory) that two processes 
finish in the same second.

Any suggestions, please?



More information about the Python-list mailing list