Mag*_*ter 3 python regex string case-insensitive ends-with
我正在寻找的等价物find $DIR -iname '*.mp3',但我不想做怪异的['mp3', 'Mp3', MP3', etc]事情。但是我不知道如何将这些re*.IGNORECASE东西与简单endswith()方法结合起来。我的目标是不遗漏单个文件,我希望最终将其扩展到其他媒体/文件类型/后缀。
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)
Run Code Online (Sandbox Code Playgroud)
TIA的任何反馈
不用理会os.walk。学习使用更简单,更出色的方法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)
Run Code Online (Sandbox Code Playgroud)
“单线”,如果您喜欢这种事情(为清晰起见,请使用多行):
sum(1 for subp in (Path('Volumes')/'audio').rglob('*')
if subp.suffix.lower() == suffix)
Run Code Online (Sandbox Code Playgroud)
你可以试试这个:)
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)
Run Code Online (Sandbox Code Playgroud)
Pythonstring.split()会将字符串分隔成一个列表,具体取决于给出的参数,并且您可以通过[-1]列表中的最后一个元素来访问后缀