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

如何仅在指定目录的子目录中搜索CSV文件

Solution to Exclude Root Directory CSV Files When Using glob

Hey there! I see you want to grab only the CSV files inside subdirectories of ./directory/src_folder, while excluding the ones directly in that root folder. Let me show you two straightforward ways to make this work:

Method 1: Adjust the glob Pattern Directly

You can tweak your glob pattern to only match CSV files that live in at least one subdirectory. This way, glob won't even return the root-level CSV files in the first place.

import glob

path = "./directory/src_folder"
# The pattern requires at least one subdirectory: ** matches any nested path, /* matches a directory, then *.csv matches the file
csv_files = glob.glob(path + "/**/*/*.csv", recursive=True)
print(csv_files)

This pattern works because it enforces that there's at least one directory level between your target path and the CSV file. Root-level files like ./directory/src_folder/src_file1.csv won't match, since they don't have that extra directory layer.

Method 2: Filter the Results After Fetching

If you prefer to keep the original glob pattern (maybe for flexibility later), you can filter the results to remove any files that are directly in the root of your target directory.

import glob
import os

path = "./directory/src_folder"
csv_files = glob.glob(path + "/**/*.csv", recursive=True)
# Keep only files where the parent directory isn't the target path itself
filtered_csv = [file for file in csv_files if os.path.dirname(file) != path]
print(filtered_csv)

This uses os.path.dirname() to check if the file's immediate parent is your target path. If it is, we exclude it; otherwise, we keep it. This works for any depth of subdirectories, not just one level.

Either of these approaches will give you the exact output you're looking for:
['./directory/src_folder/subdirectory1/subdirectory_file.csv', './directory/src_folder/subdirectory2/subdirectory_file.csv', './directory/src_folder/subdirectory3/subdirectory_file.csv']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 14:53:13