![](/img/trans.png)
[英]Python move all files from multiple subdirectories to different corresponding subdirectories
[英]Recursively move all files on subdirectories to another directory in Python
标题解释了我所追求的。 请注意,子目录不会包含任何仅目录文件(*.JPG)。 本质上,只是将文件树中的所有内容向上移动一个级别。
例如,来自~/someDir/folder1/*
, ~/someDir/folder2/*
, ... , ~/someDir/folderN/*
。 我想要将子目录的所有内容带到~/someDir/
。
shutil.move 是移动文件的好选择。
import shutil
import os
source = "/parent/subdir"
destination = "/parent/"
files_list = os.listdir(source)
for files in files_list:
shutil.move(files, destination)
对于递归移动,您可以尝试shutil.copytree(SOURCE, DESTINATION)
。 它只是复制所有文件,如果需要,您可以手动清理源目录。
此外,您可以使用Pathlib
实现类似的功能。
from pathlib import Path
def _move_all_subfolder_files_to_main_folder(folder_path: Path):
"""
This function will move all files in all subdirectories to the folder_path dir.
folder_path/
1/
file1.jpg
file2.jpg
2/
file4.jpg
outputs:
folder_path/
file1.jpg
file2.jpg
file4.jpg
"""
if not folder_path.is_dir():
return
for subfolder in folder_path.iterdir():
for file in subfolder.iterdir():
file.rename(folder_path / file.name)
用法是:
_move_all_subfolder_files_to_main_folder(Path('my_path_to_main_folder'))
使用这个,如果文件具有相同的名称,新名称将具有由 '_' 连接的文件夹名称
import shutil
import os
source = 'path to folder'
def recursive_copy(path):
for f in sorted(os.listdir(os.path.join(os.getcwd(), path))):
file = os.path.join(path, f)
if os.path.isfile(file):
temp = os.path.split(path)
f_name = '_'.join(temp)
file_name = f_name + '_' + f
shutil.move(file, file_name)
else:
recursive_copy(file)
recursive_copy(source)
这是修改后的方法以及重复检查:
src = r'D:\TestSourceFolder'
dst = r'D:\TestDestFolder'
for root, subdirs, files in os.walk(src):
for file in files:
path = os.path.join(root, file)
print("Found a file: "+path)
print("Only name of the file: "+file)
print("Will be moved to: "+os.path.join(dst, file))
# If there is no duplicate file present, then move else don't move
if not os.path.exists(os.path.join(dst, file)):
#shutil.move(path, os.path.join(dst, os.path.relpath(path, src)))
shutil.move(path, os.path.join(dst, file) )
print("1 File moved : "+file+"\n")
else:
print("1 File not moved because duplicate file found at: "+path+"\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.