tdiaz

(?) Python Pathname Change Question

Sep 24th, 2019
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. # This checks for an existing path+file exists.
  2. # so the full file path intending to be written
  3. # /Volumes/Drive/Directory/File.ext
  4. #
  5. #If 'File.ext' already exists at /Volume/Drive/Directory
  6. # The next would be:
  7. # /Volumes/Drive/Directory/File01.ext
  8. # /Volumes/Drive/Directory/File02.ext
  9. # /Volumes/Drive/Directory/File03.ext
  10. #
  11. # I want to increment the directory path instead of
  12. # the filename instead:
  13. # /Volumes/Drive/Directory01/File.ext
  14. # ...if that exists then next:
  15. # /Volumes/Drive/Directory02/File.ext
  16. #
  17. # Any takers? :)
  18. # Thanks!
  19.  
  20.  
  21.   def _rename(self, old_filename, metadata):
  22.         new_filename, ext = os.path.splitext(
  23.             self.make_filename(old_filename, metadata))
  24.  
  25.         if old_filename == new_filename + ext:
  26.             return old_filename
  27.  
  28.         new_dirname = os.path.dirname(new_filename)
  29.         if not os.path.isdir(new_dirname):
  30.             os.makedirs(new_dirname)
  31.         tmp_filename = new_filename
  32.         i = 1
  33.         while (not pathcmp(old_filename, new_filename + ext)
  34.                and os.path.exists(new_filename + ext)):
  35.             new_filename = "%s (%d)" % (tmp_filename, i)
  36.             i += 1
  37.         new_filename = new_filename + ext
  38.         log.debug("Moving file %r => %r", old_filename, new_filename)
  39.         shutil.move(old_filename, new_filename)
  40.         return new_filename
Advertisement
Add Comment
Please, Sign In to add comment