对于每个目录中的每个文件 python
for every file in every directory python
我想制作一个程序,搜索特定的 file/extension 或检查文件本身。
我从 'C:\' 开始,我想对子目录中的每个文件调用该过程,因此遍历整个 pc 文件。我以前用过os.listdir(),但是没用,这段代码能用吗?
for path, directories, files in os.walk('C:\'):
for file in files:
try:
#finding the file
except: pass
请给我更多的建议...
所有函数return文件路径
这将找到第一个匹配项:
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()
更有效。
如果你除了 "just searching the file" 之外什么都不想要,os.walk()
是最好的选择。
我想制作一个程序,搜索特定的 file/extension 或检查文件本身。 我从 'C:\' 开始,我想对子目录中的每个文件调用该过程,因此遍历整个 pc 文件。我以前用过os.listdir(),但是没用,这段代码能用吗?
for path, directories, files in os.walk('C:\'):
for file in files:
try:
#finding the file
except: pass
请给我更多的建议...
所有函数return文件路径
这将找到第一个匹配项:
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()
更有效。
如果你除了 "just searching the file" 之外什么都不想要,os.walk()
是最好的选择。