movefilesafterdownload.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import os
  2. from .common import PostProcessor
  3. from ..compat import shutil
  4. from ..utils import (
  5. PostProcessingError,
  6. make_dir,
  7. )
  8. class MoveFilesAfterDownloadPP(PostProcessor):
  9. def __init__(self, downloader=None, downloaded=True):
  10. PostProcessor.__init__(self, downloader)
  11. self._downloaded = downloaded
  12. @classmethod
  13. def pp_key(cls):
  14. return 'MoveFiles'
  15. def run(self, info):
  16. dl_path, dl_name = os.path.split(info['filepath'])
  17. finaldir = info.get('__finaldir', dl_path)
  18. finalpath = os.path.join(finaldir, dl_name)
  19. if self._downloaded:
  20. info['__files_to_move'][info['filepath']] = finalpath
  21. make_newfilename = lambda old: os.path.join(finaldir, os.path.basename(old))
  22. for oldfile, newfile in info['__files_to_move'].items():
  23. if not newfile:
  24. newfile = make_newfilename(oldfile)
  25. if os.path.abspath(oldfile) == os.path.abspath(newfile):
  26. continue
  27. if not os.path.exists(oldfile):
  28. self.report_warning(f'File "{oldfile}" cannot be found')
  29. continue
  30. if os.path.exists(newfile):
  31. if self.get_param('overwrites', True):
  32. self.report_warning(f'Replacing existing file "{newfile}"')
  33. os.remove(newfile)
  34. else:
  35. self.report_warning(
  36. f'Cannot move file "{oldfile}" out of temporary directory since "{newfile}" already exists. ')
  37. continue
  38. make_dir(newfile, PostProcessingError)
  39. self.to_screen(f'Moving file "{oldfile}" to "{newfile}"')
  40. shutil.move(oldfile, newfile) # os.rename cannot move between volumes
  41. info['filepath'] = finalpath
  42. return [], info