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

如何利用可调整数组判断文件名后缀并实现PDF文件归类?

解决动态多结尾匹配的PDF文件归类问题

问题核心

Python的str.endswith()方法不支持直接传入列表作为参数,它仅接受单个字符串或字符串元组,这就是你直接传sort_by列表不生效的原因。

解决方案

把你的sort_by列表转换成元组,直接传给endswith()即可实现“匹配任意结尾”的需求,完全适配动态调整的数组。

完整代码示例

结合你的PDF排序场景,完整实现逻辑如下:

import os
import shutil

# 可动态调整的目标结尾规则
sort_by = ["x", "z"]
# 转换为元组,适配endswith方法的参数要求
target_endings = tuple(sort_by)

# 遍历目标文件夹(替换为你的实际文件夹路径)
for file_name in os.listdir("./pdf_files"):
    file_path = os.path.join("./pdf_files", file_name)
    # 仅处理PDF文件
    if os.path.isfile(file_path) and file_name.lower().endswith(".pdf"):
        # 检查文件名是否匹配任意目标结尾
        if file_name.endswith(target_endings):
            # 找到当前文件匹配的结尾标识
            matched_tag = next(tag for tag in sort_by if file_name.endswith(tag))
            # 构建目标文件夹路径
            dest_dir = os.path.join("./pdf_files", f"{matched_tag}_docs")
            # 文件夹不存在则创建
            if not os.path.exists(dest_dir):
                os.makedirs(dest_dir)
            # 移动文件到对应文件夹
            shutil.move(file_path, os.path.join(dest_dir, file_name))

关键细节说明

  • 元组转换:tuple(sort_by)把动态列表转成endswith()支持的参数类型,底层会自动遍历元组内的所有元素做匹配,比手动写多个or高效且易维护。
  • 匹配标识获取:用next()遍历sort_by找到对应的结尾标签,确保文件能精准移动到对应文件夹,不管sort_by后续怎么增删元素都无需修改逻辑。
  • PDF过滤:增加.lower().endswith(".pdf")是为了兼容大小写不同的PDF后缀(比如.PDF),避免遗漏文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:54:16