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