Created
September 10, 2016 00:59
-
-
Save campaul/ceb1b208a4c0513ad1425278326a8f3b to your computer and use it in GitHub Desktop.
Generates unique filenames.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Generates a new unique filename if the provided filename already exists, | |
# otherwise just return the provided filename. | |
# Usage: python unique.py name/of/file | |
import os | |
import sys | |
def increment(filename): | |
last = filename.split()[-1] | |
try: | |
# If the filename ends in a number increment that number | |
num = int(last) | |
new = filename.rstrip(last) + str(num + 1) | |
except ValueError: | |
# If the filename doesn't end in a number append one | |
new = ' '.join([filename, '1']) | |
return new | |
def unique(filename): | |
while os.path.exists(filename): | |
filename = increment(filename) | |
return filename | |
def main(): | |
print(unique(sys.argv[1])) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment