如何对给定后缀的文件执行不区分大小写的搜索?

2024-06-09 01:02:18 发布

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

我正在寻找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)

TIA是否有任何反馈


Tags: inimportreforifoscountdir
3条回答

.endswith等价的正则表达式是$符号

使用上面的例子,你可以这样做

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

虽然这样做可能更准确

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

这确保文件名以.mp3结尾,而不是拾取test.amp3之类的文件

这是一个不需要正则表达式的情况的很好的例子——因此,尽管欢迎您从这些例子中学习,但值得考虑其他回答者提供的替代方案

不要为os.walk而烦恼。学习使用the easier, awesome ^{}代替。像这样:

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)

你可以试试这个:)

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]访问后缀

相关问题 更多 >