os.walk
返回一個發電機,創建值(的current_path,在目錄中的current_path,在文件的current_path)的元組。
每次調用生成器時,它都會遞歸地跟隨每個目錄,直到沒有其他子目錄可用於初始目錄,該目錄將被調用。
因此,
os.walk('C:\dir1\dir2\startdir').next()[0] # returns 'C:\dir1\dir2\startdir'
os.walk('C:\dir1\dir2\startdir').next()[1] # returns all the dirs in 'C:\dir1\dir2\startdir'
os.walk('C:\dir1\dir2\startdir').next()[2] # returns all the files in 'C:\dir1\dir2\startdir'
所以
import os.path
....
for path, directories, files in os.walk('C:\dir1\dir2\startdir'):
if file in files:
print 'found %s' % os.path.join(path, file)
或本
def search_file(directory = None, file = None):
assert os.path.isdir(directory)
for cur_path, directories, files in os.walk(directory):
if file in files:
return os.path.join(directory, cur_path, file)
return None
,或者如果你想尋找的文件,你可以這樣做:
import os
def search_file(directory = None, file = None):
assert os.path.isdir(directory)
current_path, directories, files = os.walk(directory).next()
if file in files:
return os.path.join(directory, file)
elif directories == '':
return None
else:
for new_directory in directories:
result = search_file(directory = os.path.join(directory, new_directory), file = file)
if result:
return result
return None
爲什麼我這應該是一個減1?我做錯什麼了嗎? – Baf