Python实现Linux下文件查找

 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()函数在这里使用绝对路径!

原文地址:https://www.cnblogs.com/freyr/p/4481634.html