当文件共享非常相似的名称时,如何使用pathlib.glob()遍历文件

2024-04-26 15:07:20 发布

您现在位置:Python中文网/ 问答频道 /正文

My Directory看起来像这样:

P1_AAA_NOT_SAMPLE.csv
P1_AAA_SAMPLE.csv
P1_BBB_NOT_SAMPLE.csv
P1_BBB_SAMPLE.csv
P1_CCC_NOT_SAMPLE.csv
P1_CCC_SAMPLE.csv

P2_AAA_NOT_SAMPLE.csv
P2_AAA_SAMPLE.csv
P2_BBB_NOT_SAMPLE.csv
P2_BBB_SAMPLE.csv
P2_CCC_NOT_SAMPLE.csv
P2_CCC_SAMPLE.csv

如果我只想捕获示例文件(即,我不想要非示例文件),如何使用pathlib.glob()遍历此目录中的文件

我的代码如下所示:

from pathlib import Path

file_path = r'C:\Users\HP\Desktop\My Directory'

for fle in Path(file_path).glob('P*_*_SAMPLE.csv'):
    # do something with each SAMPLE file

但这段代码也将捕获示例文件和非示例文件。是否有办法调整通配符或glob()部分,以便只捕获样本文件,最好使用pathlib

提前谢谢


Tags: 文件csvsample示例mynotdirectoryglob
2条回答

类似这样,如果文件名中的“not”,则执行以下操作

在您的for循环之后

for fle in Path(file_path).glob('P*_*_SAMPLE.csv'):
    if 'NOT' not in str(file):
        #do something

可以在生成器表达式(或列表)中进行筛选,如下所示:

for fle in (p for p in Path(file_path).glob('P*_*_SAMPLE.csv') if 'NOT_SAMPLE' not in str(p)):

或在以下情况之前建立一个列表:

valid_paths = [p for p in Path(file_path).glob('P*_*_SAMPLE.csv') if 'NOT_SAMPLE' not in str(p)]

for fle in valid_paths:

相关问题 更多 >