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

如何用Python筛选排除含特定字符串路径的.c文件?

解决路径筛选.c文件的Python代码问题

你的需求是筛选出文件路径中不包含"abc"、"myfiles"、"new"这三个字符串的.c文件,但原代码的逻辑错误导致无法得到预期结果,以下是问题分析和修正方案:

原代码的核心问题

  1. 条件判断逻辑错误:
    原代码中的if "new" or "myfiles" or "abc" not in source写法完全不符合预期。因为非空字符串在布尔判断中会被视为True,所以这个条件等价于if True or True or (abc not in source),永远为真,导致所有.c文件都会被复制,不管路径是否包含要排除的关键词。

  2. 未处理目标文件夹不存在的情况:
    如果destination_folder还未创建,shutil.copy会直接抛出异常中断程序。

  3. 未处理同名文件覆盖问题:
    不同子文件夹中的同名.c文件会在目标文件夹中互相覆盖,导致文件丢失。

修正后的代码

import os
import shutil

path = "C:\\Users\\Downloads\\All_h_files\\"
destination_folder = "C:\\Users\\Downloads\\All_h"

# 确保目标文件夹存在,不存在则自动创建
os.makedirs(destination_folder, exist_ok=True)

for root, dirs, files in os.walk(path):
    for file in files:
        source = os.path.join(root, file)
        # 先判断是否是.c文件,再检查路径是否不含所有排除关键词
        if file.endswith(".c") and not any(keyword in source for keyword in ["abc", "myfiles", "new"]):
            # 保留原文件夹结构,避免同名文件覆盖
            relative_root = os.path.relpath(root, path)
            target_subfolder = os.path.join(destination_folder, relative_root)
            os.makedirs(target_subfolder, exist_ok=True)
            destination = os.path.join(target_subfolder, file)
            shutil.copy(source, destination)

print("符合条件的文件已复制完成!")

关键修改说明

  • 修正条件判断:使用not any(keyword in source for keyword in ["abc", "myfiles", "new"])来确保路径中不包含任何要排除的关键词,逻辑准确且简洁。
  • 自动创建文件夹:通过os.makedirs(..., exist_ok=True)自动创建目标文件夹及所需的子文件夹,避免因文件夹不存在导致的异常。
  • 避免文件覆盖:保留原文件的相对路径结构,在目标文件夹下重建对应的子文件夹,确保不同路径下的同名文件不会互相覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:40:22