最新消息:时间抓起来说是金子,抓不住就是流水。

使用Python从指定的搜索路径寻找文件

Python 老子黑牵翻 4739浏览 0评论

       通过python可以给定一个搜索路径(一个描述目录信息的字符串),需要根据这个路径和请求的文件名找到第一个符合要求的文件

具体代码如下:

import os
def search_file(filename,search_path,pathsep=os.pathsep):
 """ 给定一个搜索路径,根据请求的名字找到文件 """
 for path in search_path.split(pathsep):
  candidate = os.path.join(path,filename)
  if os.path.isfile(candidate):
   return os.path.abspath(candidate)
 return None
if __name__ == '__main__':
 search_path = '/bin' + os.pathsep + '/usr/bin' # ; on Windows, :on UNIX
 find_file = search_file('ls', search_path)
 if find_file:
  print "File 'ls' found at %s" % find_file
 else:
  print "File 'ls' not found"

 

用python编译以后,发现ls这个字符串在的路径在

File 'ls' found at /bin/ls

 

转载请注明:LINUX服务器运维架构技术分享 » 使用Python从指定的搜索路径寻找文件

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址