1 import os, sys 2 3 4 def search(curpath, s): 5 L = os.listdir(curpath) #列出當前目錄下所有文件 6 for subpath in L: #遍歷當前目錄所有文件 7 if os.path.isdir(os.path.join(curpath, subpath)): #若文件仍為目錄,遞歸查找子目錄 8 newpath = os.path.join(curpath, subpath) 9 search(newpath, s) 10 elif os.path.isfile(os.path.join(curpath, subpath)): #若為文件,判斷是否包含搜索字串 11 if s in subpath: 12 print os.path.join(curpath, subpath) 13 14 def main(): 15 workingpath = os.path.abspath('.') 16 s = sys.argv[1] 17 search(workingpath, s) 18 19 if __name__ == '__main__': 20 main()
PS: 關鍵分析紅字部分
如果直接使用 subpath ,因它只是一個文件名,故判斷它是否為目錄語句 os.path.isdir(subpath) 只會在當前目錄下查找subpath文件;而不會隨着search的遞歸而自動在更新路徑下查找。比如:
+/home/freyr/
|
|--------dir1/
| |
| |-------file1
| |-------file2
|
|--------dir2/
|
|--------file2
Step1、在主目錄下遍歷,subpath = dir1時,先判斷是否為目錄:os.path.isdir(subpath)其實就是os.path.isdir('/home/freyr/dir1')
Step2、dir1為目錄,遍歷dir1。subpath = file1時,同樣先判斷是否為目錄:os.path.isdir(subpath)其實是os.path.isdir('/home/freyr/file1'),而不是os.path.isdir('/home/freyr/dir1/file1'),很明顯/home/freyr下沒有file1文件。這樣造成的后果就是除了當前目錄(一級目錄)文件(如file2)可以搜索到,子目錄內文件都是沒有搜索到的,因為它每次都是跑到/home/freyr下搜索文件名
其實簡單的說,os.path.isdir()函數在這里使用絕對路徑!