Skip to content

Instantly share code, notes, and snippets.

@OmarArain
Created January 9, 2014 16:54
Show Gist options
  • Save OmarArain/8337627 to your computer and use it in GitHub Desktop.
Save OmarArain/8337627 to your computer and use it in GitHub Desktop.
if file exists, adds an '_1' to filename. If '_x' (where x is a number) exists, then it increments x. Intelligent renaming of filepaths?
def change_filepath_if_exists(filepath):
f, ext = os.path.splitext(filepath)
if os.path.exists(filepath):
if f[f.rfind('_')+1:].isdigit():
oldnum = f[f.rfind('_')+1:]
newnum = str(int(oldnum)+1)
newf = f[0:-len(oldnum)] + newnum
f = newf
print('1')
else:
f = f + '_1'
print('2')
print(f)
return change_filepath_if_exists(f+ext)
else:
return f+ext
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment