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)

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值