0

我想返回文件的路径,如果程序找到它,但我希望它继续循环(或递归重复)程序,直到检查所有文件。

def findAll(fname, path):
for item in os.listdir(path):
    n = os.path.join(path, item)
    try:
        findAll(n, fname)
    except:
        if item == fname:
            print(os.idontknow(item))

所以我在调用路径时遇到了麻烦,现在我有

os.idontknow(item) 

作为占位符

输入是:

findAll('fileA.txt', 'testpath')

输出是:

['testpat\\fileA.txt', 'testpath\\folder1\\folder11\\fileA.txt','testpath\\folder2\\fileA.txt']
4

2 回答 2

2

根据我上面的评论,这是一个示例,它将从当前目录开始并搜索所有子目录,寻找匹配的文件fname

import os

# path is your starting point - everything under it will be searched
path = os.getcwd()    
fname = 'file1.txt'
my_files = []

# Start iterating, and anytime we see a file that matches fname,
# add to our list    
for root, dirs, files in os.walk(path):
  for name in files:
    if name == fname:
      # root here is the path to the file
      my_files.append(os.path.join(root, name))

print my_files

或者作为一个函数(更适合你的情况:)):

import os

def findAll(fname, start_dir=os.getcwd()):
  my_files = []
  for root, dirs, files in os.walk(start_dir):
    for name in files:
      if name == fname:
        my_files.append(os.path.join(root, name))
  return my_files


print findAll('file1.txt')
print findAll('file1.txt', '/some/other/starting/directory')
于 2012-11-05T04:09:24.190 回答
1

像这样的东西,也许?

import os
path = "path/to/your/dir"
for (path, dirs, files) in os.walk(path):
    print files
于 2012-11-05T04:04:43.097 回答