I am writing code that increments the number at the end of a file name until it no longer overwrites the existing file. I create several files, all with the same base file name, but with different extensions, none of which I want to overwrite.
Naive version:
prefix = 'hello0' while os.path.exists(prefix + '.abc') or os.path.exists(prefix + '.def') or os.path.exists(prefix + '.ghi'): n = int(prefix[-1]) prefix = prefix[:-1] + str(n + 1)
The condition can obviously be very long and ugly if there are several extensions. I rendered this in a for loop.
My version:
prefix = 'hello0' extensions = ('.abc', '.def', '.ghi') # there could be even more than this condition = True while condition: condition = False # if any of the paths still exist, set the condition back to True for extension in extensions: if os.path.exists(prefix + extension): condition = True n = int(prefix[-1]) prefix = prefix[:-1] + str(n + 1)
I still feel this is a bit awkward: it's not entirely clear what the while is actually testing. Is it possible to build a boolean expression dynamically and not set a boolean?
I think the following may work (I have not tested it, I only thought about it when writing this!), But I don’t think I need to resort to eval :
prefix = 'hello0' extensions = ('.abc', '.def', '.ghi') test = 'False' for extension in extensions: test += " or os.path.exists(prefix + '" + extension + "')" while eval(test): n = int(prefix[-1]) prefix = prefix[:-1] + str(n + 1)
source share