簡體   English   中英

如何從文件夾中選擇帶有編號擴展名的文件?

[英]How to select files with numbered extensions from a folder?

我正在嘗試為項目構建自己的數據集。 因此,我需要選擇已從另一個程序導出並帶有編號擴展名的文件:

exported_file_1_aaa.001
exported_file_2_aaa.002
exported_file_3_aaa.003
...
exported_file_5_zzz.925
...and so on.

我知道如何從文件夾中選擇具有特定擴展名的文件,例如“ .txt”,並將其附加到列表或字典中。 有什么辦法可以解決'.nnn'

ext = '.nnn'
all_files = [i for i in os.listdir(dir) if os.path.splitext(i)[1] == ext]
for f in all_files:
    ...

您可以混合使用shell globlob( glob )和regex( re )的功能。

使用glob您可以獲取以數字結尾的文件,以便我們獲得數量有限的文件,以供re執行最終檢查:

glob.iglob('exported_file_*.*[0-9]')

然后,我們可以使用Regex模式精確匹配文件:

\.\d+$

這將匹配以last結尾的數字結尾的文件名.

放在一起:

import glob
import re
[file for file in glob.iglob('exported_file_*.*[0-9]') if re.search(r'\.\d+$', file)]

Shell globbing不像re那樣靈活,否則我們僅用glob就可以完成。

另外,如果您確定所有文件都以一定位數結尾,則glob僅適用於例如last后面以3位數結尾的文件.

glob.iglob('exported_file_*.[0-9][0-9][0-9]')

如果您不關心擴展名的長度,則可以使用isdigit方法:

all_files = [i for i in os.listdir(dir) if os.path.splitext(i)[1].isdigit()]
for f in all_files: 
    ....

您可以使用glob模塊。

import glob

my_dir = "mydir"

all_files = [fn for fn in glob.glob(f"{my_dir}/*.[0-9][0-9][0-9]")]

暫無
暫無

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

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