python 把文件夹及子文件夹内的所有文件移动到指定文件夹中
python 把文件夹及子文件夹内的所有文件移动到指定文件夹中。批量移动文件
·
python 把文件夹及子文件夹内的所有文件移动到指定文件夹中
【1】提取路径下所有文件到指定文件夹下
import shutil
import os
def move_files(source, dest):
for root, dirs, files in os.walk(source):
for file in files:
source_path = os.path.join(root, file)
destination_path = os.path.join(dest, file)
shutil.move(source_path, destination_path)
# 请填写要移动的源文件夹和目标文件夹的路径
source_folder = "old"
destination_folder = "new_20230401"
move_files(source_folder, destination_folder)
【2】提取路径下所有指定后缀文件到指定文件夹下 ,以.txt为例
import shutil
import os
def move_txt_files(source, dest):
for root, dirs, files in os.walk(source):
for file in files:
if file.endswith('.txt'):
source_path = os.path.join(root, file)
destination_path = os.path.join(dest, file)
shutil.move(source_path, destination_path)
# 请填写要移动的源文件夹和目标文件夹的路径
source_folder = "src_folder"
destination_folder = "dst_folder"
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
move_txt_files(source_folder, destination_folder)
【3】留言提到了不同文件夹下存在同名文件,想都保存下来。
建议直接将分散在各个文件夹内的原始文件,缀加文件夹名后重命名再移动,这样既保留了所有文件,又知道原始出处。如下:
import shutil
import os
def move_files(source, dest):
for root, dirs, files in os.walk(source):
for file in files:
source_path = os.path.join(root, file)
file_name, file_ext = os.path.splitext(file)
folder_name = os.path.basename(root)
new_file_name = f"{file_name}_{folder_name}{file_ext}"
destination_path = os.path.join(dest, new_file_name)
shutil.move(source_path, destination_path)
#
source_folder = "old"
destination_folder = "new"
move_files(source_folder, destination_folder)
【4】接上述第3,如果非要仅对同名的文件进行重命名。那就需要在移动每一个文件时对目标文件夹再重新遍历,相比3对多出n倍工作量。如下:
import shutil
import os
def move_files(source, dest):
for root, dirs, files in os.walk(source):
for file in files:
source_path = os.path.join(root, file)
file_name, file_ext = os.path.splitext(file)
folder_name = os.path.basename(root)
new_file_name = f"{file_name}{file_ext}"
destination_path = os.path.join(dest, new_file_name)
#遍历查找同名文件
while os.path.exists(destination_path):
new_file_name = f"{file_name}_{folder_name}{file_ext}"
destination_path = os.path.join(dest, new_file_name)
shutil.move(source_path, destination_path)
#
source_folder = "old"
destination_folder = "new"
move_files(source_folder, destination_folder)
更多推荐
所有评论(0)