Skip to content

Instantly share code, notes, and snippets.

@campaul
Created September 10, 2016 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save campaul/ceb1b208a4c0513ad1425278326a8f3b to your computer and use it in GitHub Desktop.
Save campaul/ceb1b208a4c0513ad1425278326a8f3b to your computer and use it in GitHub Desktop.
Generates unique filenames.
# 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