首页 > 解决方案 > 在文件名中的任意位置搜索字符串,不区分大小写。蟒蛇 3

问题描述

环境:Python 3.6,操作系统:Windows 10

我有以下代码将搜索在文件名的开头 ( .startswith) 或文件名 ( .endswith) 的结尾包含字符串的文件名,包括子目录并且区分大小写,即searchText = 'guess'searchText = 'Guess'.

我想修改if FILE.startswith(searchText):它允许在文件名中的任何位置进行搜索并且不区分大小写。这可能吗?

例如,一个目录包含两个名为GuessMyNumber.py和的文件guessTheNumber.py。我想搜索'my'并返回文件名的代码GuessMyNumber.py

#!/usr/bin/env python3
import os

#  set text to search for 
searchText = 'Guess'

#   the root (top of tree hierarchy) to search, remember to change \ to / for Windows
TOP = 'C:/works'

found = 0

for root, dirs, files in os.walk(TOP, topdown=True, onerror=None, followlinks=True):

        for FILE in files:
            if FILE.startswith(searchText):
                print ("\nFile {} exists..... \t\t{}".format(FILE, os.path.join(root)))
                found += 1

            else:
                pass

print('\n File containing \'{}\' found {} times'.format(searchText, found))

谢谢大家,汤米。

标签: python-3.x

解决方案


一种基于简单glob的方法:

#!/usr/bin/env python3
import os
import glob


#  set text to search for 
searchText = 'Guess'

#   the root (top of tree hierarchy) to search, remember to change \ to / for Windows
TOP = 'C:/works'

found = 0
for filename in glob.iglob(os.path.join(TOP, '**', f'*{searchText}*'), recursive=True):
    print ("\nFile {} exists..... \t\t{}".format(filename, os.path.dirname(filename)))
    found += 1


print('\n File containing \'{}\' found {} times'.format(searchText, found))

一种基于简单fnmatch的方法:

#!/usr/bin/env python3
import os
import fnmatch


#  set text to search for 
searchText = 'Guess'

#   the root (top of tree hierarchy) to search, remember to change \ to / for Windows
TOP = 'C:/works'

found = 0
for root, dirnames, filenames in os.walk(TOP, topdown=True, onerror=None, followlinks=True):
    for filename in filenames:
        if fnmatch.fnmatch(filename, f'*{searchText}*'):
            print ("\nFile {} exists..... \t\t{}".format(filename, os.path.join(root)))
            found += 1

print('\n File containing \'{}\' found {} times'.format(searchText, found))

您还可以使用 PERL 兼容(更通用)的正则表达式来代替andre支持的 POSIX 兼容(不太通用)。但是,在这个简单的场景中,兼容 POSIX 就绰绰有余了。globfnmatch


推荐阅读