Save to a file, but avoid overwriting an existing file

Skip Montanaro skip at pobox.com
Wed Mar 12 08:37:44 EDT 2014


This seems to be an application-level decision. If so, in your
application, why not just check to see if the file exists, and
implement whatever workaround you deem correct for your needs? For
example (to choose a simple, but rather silly, file naming strategy):

fname = "x"
while os.path.exists(fname):
    fname = "%s.%f" % (fname, random.random())
fd = open(fname, "w")

It's clearly not going to be safe from race conditions, but I leave
solving that problem as an exercise for the reader.

Skip



More information about the Python-list mailing list