Save to a file, but avoid overwriting an existing file
Dave Angel
davea at davea.name
Wed Mar 12 14:22:51 EDT 2014
zoom <zoom at yahoo.com> Wrote in message:
> 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.
>
The tempfile module is your best answer, but if you really need
to keep the file afterwards, you'll have the same problem when
you rename it later.
I suggest you learn about try/except. For simple cases it's not
that tough, though if you want to ask about it, you'll need to
specify your Python version.
--
DaveA
More information about the Python-list
mailing list