Unique file name (counter)


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import itertools
  2. import os
  3. import re
  4.  
  5. def unique_file_name(file):
  6. ''' Append a counter to the end of file name if
  7. such file allready exist.'''
  8. if not os.path.isfile(file):
  9. # do nothing if such file doesn exists
  10. return file
  11. # test if file has extension:
  12. if re.match('.+\.[a-zA-Z0-9]+$', os.path.basename(file)):
  13. # yes: append counter before file extension.
  14. name_func = \
  15. lambda f, i: re.sub('(\.[a-zA-Z0-9]+)$', '_%i\\1' % i, f)
  16. else:
  17. # filename has no extension, append counter to the file end
  18. name_func = \
  19. lambda f, i: ''.join([f, '_%i' % i])
  20. for new_file_name in \
  21. (name_func(file, i) for i in itertools.count(1)):
  22. if not os.path.exists(new_file_name):
  23. return new_file_name

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.