Moving all files from one directory to another using Python
suprised this doesn't have an answer using pathilib which was introduced in python 3.4
+
additionally, shutil updated in python 3.6
to accept a pathlib object more details in this PEP-0519
Pathlib
from pathlib import Pathsrc_path = '\tmp\files_to_move'for each_file in Path(src_path).glob('*.*'): # grabs all files trg_path = each_file.parent.parent # gets the parent of the folder each_file.rename(trg_path.joinpath(each_file.name)) # moves to parent folder.
Pathlib & shutil to copy files.
from pathlib import Pathimport shutilsrc_path = '\tmp\files_to_move'trg_path = '\tmp'for src_file in Path(src_path).glob('*.*'): shutil.copy(src_file, trg_path)
Please, take a look at implementation of the copytree function which:
List directory files with:
names = os.listdir(src)
Copy files with:
for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) copy2(srcname, dstname)
Getting dstname is not necessary, because if destination parameter specifies a directory, the file will be copied into dst using the base filename from srcname.
Replace copy2 by move.