[Python] python 递归搜索文件夹下的指定文件 →→→→→进入此内容的聊天室

来自 , 2021-01-20, 写在 Python, 查看 151 次.
URL http://www.code666.cn/view/6e2290db
  1. import os
  2.  
  3. def look_in_directory(directory):
  4.     """Loop through the current directory for the file, if the current item
  5.       is a directory, it recusively looks through that folder"""
  6.  
  7.     # Loop over all the items in the directory
  8.     for f in os.listdir(directory):
  9.         # Uncomment the line below to see how the files/folders are searched
  10.         # print "Looking in " + directory
  11.  
  12.         # If the item is a file check to see if it is what we are looking
  13.         # for, if it is, print that we found it and return true
  14.         if os.path.isfile(os.path.join(directory, f)):
  15.             if f == file_to_find:
  16.                 print "Found file: " + os.path.join(directory, f)
  17.                 return True
  18.  
  19.         # If the item is a directory, we recursivley look through that
  20.         # directory if it is found, we again return true
  21.         if os.path.isdir(os.path.join(directory, f)):
  22.             if look_in_directory(os.path.join(directory, f)):
  23.                 return True
  24.  
  25. # we will look for the file recursively
  26. file_to_find = "jono.png"
  27. # Start looking in the home directory (~)
  28. # If it is not found, ie it did not return True, tell the user it was "Not
  29. # Found"
  30. if look_in_directory(os.path.expanduser("~")) != True:
  31.     print "Not Found"
  32. #//python/2372

回复 "python 递归搜索文件夹下的指定文件"

这儿你可以回复上面这条便签

captcha