返回文本文件路径

时间:2012-11-05 03:56:11

标签: python recursion path

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

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']

2 个答案:

答案 0 :(得分: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')

答案 1 :(得分:0)

这样的事,也许吧?

import os
path = "path/to/your/dir"
for (path, dirs, files) in os.walk(path):
    print files