我试图递归地遍历目录并查找与特定模式匹配的文件。我的代码的相关代码段是:
import sys, os, xlrd, fnmatch
for root, dirnames, filenames in os.walk('/myfilepath/'):
for dir in dirnames:
os.chdir(os.path.join(root, dir))
for filename in fnmatch.filter(filenames, 'filepattern*'):
print os.path.abspath(filename)
print os.getcwd()
print filename
wb = xlrd.open_workbook(filename)
我的打印行显示
os.getcwd()
等于文件名的目录,所以对我来说似乎应该找到该文件,但是当第一个模式匹配时,IOError: [Errno 2] No such file or directory
会为wb = xlrd.open_workbook(filename)
抛出。 最佳答案
从dirnames
返回的os.walk
不代表filenames
所在的目录。相反,root
表示filenames
所在的目录。对于您的应用程序,您可以有效地忽略directories
返回。
尝试这样的事情:
import os
import fnmatch
for root, _, filenames in os.walk('/tmp'):
print root, filenames
for filename in fnmatch.filter(filenames, '*.py'):
filename = os.path.join(root, filename)
# `filename` now unambiguously refers to a file that
# exists. Open it, delete it, xlrd.open it, whatever.
# For example:
if os.access(filename, os.R_OK):
print "%s can be accessed" % filename
else:
print "%s cannot be accessed" % filename
另外:在
os.chdir()
迭代中调用os.walk()
可能并不安全。如果os.walk()
的参数是相对的,则尤其如此。关于python - 在文件的当前目录中时,Python os.walk/fnmatch.filter找不到文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32746367/