Does Python have any built-in functionality to add a number to a filename if it already exists?
My idea is that it would work the way certain OS’s work – if a file is output to a directory where a file of that name already exists, it would append a number or increment it.
I.e: if “file.pdf” exists it will create “file2.pdf”, and next time “file3.pdf”.
In a way, Python has this functionality built into the
tempfilemodule. Unfortunately, you have to tap into a private global variable,tempfile._name_sequence. This means that officially,tempfilemakes no guarantee that in future versions_name_sequenceeven exists — it is an implementation detail.But if you are okay with using it anyway, this shows how you can create uniquely named files of the form
file#.pdfin a specified directory such as/tmp: