import os
def find(name, path="C:\\"):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
这将查找所有匹配项:
def find_all(name, path="C:\\"):
result = []
for root, dirs, files in os.walk(path):
if name in files:
result.append(os.path.join(root, name))
return result
这将符合一种模式:
import os
import fnmatch
def find(pattern, path="C:\\"):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
所有函数都返回文件路径
这将找到第一个匹配项:
这将查找所有匹配项:
这将符合一种模式:
当且仅当您希望到处搜索时,此代码将工作,并且比
os.listdir()
更高效。 如果除了“只搜索文件”之外,您不需要其他任何东西,os.walk()
是最好的选择相关问题 更多 >
编程相关推荐