You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何筛选纯数字命名文件夹并按规则匹配复制对应文件

目录结构
post
-----1
------10am
-----------images
-----2
-------10am
-----------images
-----3
------10am
-----------images

最多存在编号为31的纯数字命名文件夹,每个数字文件夹下固定有10am子文件夹,10am下固定有images子文件夹。

功能需求
  • 所有待复制的图片、txt文件存放在单独目录中,命名规则为数字.后缀,比如2.jpg、2.txt
  • 编号为N的图片需复制到post/N/10am/images路径
  • 编号为N的txt文件需复制到post/N/10am路径
  • 需忽略10am、images这类非纯数字命名的文件夹
现有问题说明
  • 无法筛选纯数字命名的文件夹
  • 路径拼接写法硬编码,存在跨平台兼容问题
  • 自定义allfiles函数仅返回第一个元素,原因是循环内执行return会直接终止函数运行,不会继续遍历后续元素
实现方案

核心筛选方法

判断文件夹/文件名是否为纯数字,直接用Python字符串内置的isdigit()方法即可,满足条件的返回True,否则返回False。

因为目录结构是固定规则的,不需要用os.walk遍历所有层级,直接遍历源文件构造目标路径的方案效率更高,完整实现代码如下:

import os
import shutil

# 基础路径配置
sample_files_dir = r"\practice image and text"
post_root_dir = r"\posts"
time_folder = "10am"

# 遍历待复制文件目录
for filename in os.listdir(sample_files_dir):
    # 分离文件名和后缀
    name_part, ext = os.path.splitext(filename)
    # 过滤非数字命名、编号超过31的文件
    if not name_part.isdigit() or int(name_part) > 31:
        continue
    # 构造对应目标路径
    num = name_part
    target_txt_dir = os.path.join(post_root_dir, num, time_folder)
    target_img_dir = os.path.join(target_txt_dir, "images")
    # 自动创建不存在的目标文件夹
    os.makedirs(target_txt_dir, exist_ok=True)
    os.makedirs(target_img_dir, exist_ok=True)
    
    # 按文件类型复制到对应路径
    source_path = os.path.join(sample_files_dir, filename)
    if ext.lower() in (".jpg", ".jpeg", ".png"):
        shutil.copy(source_path, target_img_dir)
    elif ext.lower() == ".txt":
        shutil.copy(source_path, target_txt_dir)

补充说明

如果确实需要遍历目标目录筛选纯数字文件夹,可使用如下判断逻辑:

# 数字文件夹都在post根目录下,只需遍历第一层即可
for folder_name in os.listdir(post_root_dir):
    folder_path = os.path.join(post_root_dir, folder_name)
    # 筛选条件:是文件夹、名称为纯数字、编号≤31
    if os.path.isdir(folder_path) and folder_name.isdigit() and int(folder_name) <= 31:
        print(f"匹配到编号文件夹:{folder_name},路径为{folder_path}")

如果需要修复allfiles函数返回所有匹配文件的需求,两种改法可选:

# 改法1:返回生成器,适合处理大量文件
def allfiles(file_list):
    for file in file_list:
        name_part = os.path.splitext(file)[0]
        if name_part.isdigit():
            yield file

# 改法2:直接返回匹配结果列表
def allfiles(file_list):
    res = []
    for file in file_list:
        name_part = os.path.splitext(file)[0]
        if name_part.isdigit():
            res.append(file)
    return res

内容的提问来源于stack exchange,提问作者bradrar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:30:02