簡體   English   中英

當文件共享非常相似的名稱時如何使用 pathlib.glob() 遍歷文件

[英]How to iterate through files using pathlib.glob() when files share very similar names

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

如果我只想捕獲 SAMPLE 文件(即我不想要 NOT_SAMPLE 文件),如何使用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

但此代碼還將捕獲 SAMPLE 文件和 NOT_SAMPLE 文件。 有沒有辦法調整通配符或glob()部分以僅捕獲 SAMPLE 文件,最好使用pathlib

提前致謝。

您可以過濾生成器表達式(或列表理解),如下所示:

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:

像這樣的東西,如果文件名中的“不是”:做一些事情。

在你的 for 循環之后,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM