2017-09-06 42 views
2

我正在尋找相當於find $DIR -iname '*.mp3',我不想做奇怪的['mp3', 'Mp3', MP3', etc]事情。但我不知道如何將re*.IGNORECASE的東西與簡單的endswith()方法結合起來。我的目標是不要錯過單個文件,我想最終將其擴展到其他媒體/文件類型/後綴。如何在Python中對給定後綴的文件執行不區分大小寫的搜索?

import os 
import re 
suffix = ".mp3" 

mp3_count = 0 

for root, dirs, files in os.walk("/Volumes/audio"): 
    for file in files: 
     # if file.endswith(suffix): 
     if re.findall('mp3', suffix, flags=re.IGNORECASE): 
      mp3_count += 1 

print(mp3_count) 

TIA的任何反饋

+0

它必須是一個正則表達式的解決方案嗎?爲什麼不'pathlib.Path(file).suffix.lower()=='.mp3''? –

回答

1

你可以試試這個:)

import os 
# import re 
suffix = "mp3" 

mp3_count = 0 

for root, dirs, files in os.walk("/Volumes/audio"): 
    for file in files: 
     # if file.endswith(suffix): 
     if file.split('.')[-1].lower() == suffix: 
      mp3_count += 1 

print(mp3_count) 

Python的string.split()將字符串分隔成列表,具體取決於被賦予什麼樣的參數,你可以訪問後綴[-1],列表中的最後一個元素

+0

謝謝。簡單,這是我能夠實際工作的唯一建議。 – MagicToaster

1

不要打擾os.walk。學習改用the easier, awesome pathlib.Path。像這樣:

from pathlib import Path 

suffix = ".mp3" 

mp3_count = 0 

p = Path('Volumes')/'audio': # note the easy path creation syntax 
# OR even: 
p = Path()/'Volumes'/'audio': 

for subp in p.rglob('*'): # recursively iterate all items matching the glob pattern 
    # .suffix property refers to .ext extension 
    ext = subp.suffix 
    # use the .lower() method to get lowercase version of extension 
    if ext.lower() == suffix: 
     mp3_count += 1 

print(mp3_count) 

「的一行」,如果你進入的是諸如此類的事情(多線清晰度):

sum([1 for subp in (Path('Volumes')/'audio').rglob('*') 
    if subp.suffix.lower() == suffix]) 
+0

@Rawing使用'.rglob()'而不是'iterdir()'的好建議。相反,我編輯了答案。 –

0

正則表達式相當於.endswith$跡象。

要使用上面的示例,您可以這樣做;

re.findall('mp3$', suffix, flags=re.IGNORECASE): 

雖然這樣做可能更準確,

re.findall(r'\.mp3$', suffix, flags=re.IGNORECASE): 

這可以確保文件名以.mp3結束,而不是拿起文件,如test.amp3

這是一個非常好的例子,它並不真正需要正則表達式 - 所以當您歡迎您從這些例子中學習時,值得考慮其他答案提供的替代方案。