2012-11-05 118 views
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'] 
+2

你看過'os.walk'嗎?它走過一個目錄結構,它應該能夠處理這種情況。 – RocketDonkey

回答

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') 
0

這樣的事情,也許?

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

但我只是從基本文件和我想要查找的文本文件開始。不是整個路徑。我想返回整個路徑。 –