python-3.x - 在文件名中的任意位置搜索字符串,不区分大小写。蟒蛇 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))
谢谢大家,汤米。
解决方案
一种基于简单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 就绰绰有余了。glob
fnmatch
推荐阅读
- msbuild - 使 WIX 安装程序将文件放置在 AppData 中
- c# - c# 通过对象拆箱
- azure - 如何在 azure 中构建 200 个本地数据库?
- php - 如何在 MySQL 中使用带有连接的 CodeIgniter 使用 CASE
- c# - 我如何让用户将字符串添加到数组中,而其中已经存在字符串?(Windows 窗体)
- jquery - 添加、更新和删除 jQuery 代码不起作用
- javascript - 为什么不能“OR Throw”排队?
- actions-on-google - 仅在 SSML 中播放音频转换回复?
- c++ - 为什么我在这段代码中读取文件结尾?
- html - 使用 After 选择器时出现箭头居中问题