使用Python根据扩展名将子目录的文件移动到指定目的目录

功能说明

将源目录下子目录中的文件移动到指定目的目录。要求如下:

  • 子目录中仅包含指定扩展名的文件才会移动文件。
  • 如果目的目录已包含同名文件,将文件重命名为原文件名 13位时间戳

例如:
当前目录结构如下:

test
│  2.txt
│
├─1
│  │  1.txt
│  │
│  └─22.txt
│
├─2
│  │  3.txt
│  │
│  └─3
└─3
        2.txt

运行后的目录结构如下:

test
│  2 1618156462496.txt
│  2.txt
│
├─1
│  │  1.txt
│  │
│  └─22.txt
│
├─2
│  │  3.txt
│  │
│  └─3
└─3

仅移动了子目录3中的2.txt。由于12子目录包含子目录,因此其目录中的文件不会被移动。

代码

import os
import shutil
import time
from pathlib import Path


# 生成时间戳
def now_to_timestamp(digits=13):
    time_stamp = time.time()
    digits = 10 ** (digits - 10)
    time_stamp = int(round(time_stamp*digits))
    return time_stamp

# 移动文件
def move_files(src_dir, dest_dir, ext_filter):
    '''
    src_dir:源目录
    dest_dir:目的目录
    ext_filter:扩展名列表
    '''
    # 获取源目录中的子目录和子文件
    sub_dirs = os.listdir(src_dir)
    # 遍历子目录、子文件
    for sub_dir in sub_dirs:
        # 构造子目录路径
        sub_dir_path = os.path.join(src_dir, sub_dir)
        # 遍历当前子目录
        for root, dirs, files in os.walk(sub_dir_path):
            # 只有当前子目录下仅有文件时,继续运行
            ext_list = [i for i in files if not i.lower().endswith(ext_filter)]
            if root == sub_dir_path and len(dirs) == 0 and len(files) > 0 and len(ext_list) == 0:
                for file in files:
                    # 构造文件路径
                    file_path = os.path.join(root, file)
                    new_file_path = os.path.join(dest_dir, file)
                    # 检测文件扩展名是否符合要求
                    if Path(file_path).suffix.lower() in ext_filter:
                        # 检测目的文件路径是否存在,不存在直接移动,存在更名后再移动
                        if not os.path.exists(new_file_path):
                            pass
                        else:
                            # 重命名文件
                            new_file_name = Path(
                                new_file_path).stem + " " + str(now_to_timestamp()) + Path(new_file_path).suffix
                            new_file_path = os.path.join(
                                dest_dir, new_file_name)
                        # 移动文件
                        shutil.move(file_path, new_file_path)
                        print(file_path, '->', new_file_path)


if __name__ == '__main__':
    src_dir = r'd:\test'
    dest_dir = r'd:\test'
    exts = ('.txt')
    move_files(src_dir, dest_dir, exts)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值