python实现在目录中查找指定文件的方法

yipeiwu_com6年前Python基础

本文实例讲述了python实现在目录中查找指定文件的方法。分享给大家供大家参考。具体实现方法如下:

1. 模糊查找

复制代码 代码如下:
import os
from glob import glob #用到了这个模块
def search_file(pattern, search_path=os.environ['PATH'], pathsep=os.pathsep):
    for path in search_path.split(os.pathsep):
        for match in glob(os.path.join(path, pattern)):
            yield match
if __name__ == '__main__':
    import sys
    if len(sys.argv)<2  or sys.argv[1].startswith('-'):#sys.argv[0]是当前路径,1开始是后面的参数
        print 'Use: %s <pattern>' % sys.argv[0]
        sys.exit(1)
    if len(sys.argv)>2:
        matchs = list(search_file(sys.argv[1],sys.argv[2]))
    else:
        matchs = list(search_file(sys.argv[1]))
    print '%d match' % len(matchs)
    for match in matchs:
        print match

2. 指定的文件名精确查找
复制代码 代码如下:
import os,optparse
#1:精确查找
def search_file(filename, search_path=os.environ['PATH'], pathsep=os.pathsep):#os.pathsep是分隔符';'
    for path in search_path.split(os.pathsep):
        candidate = os.path.join(path, filename)#预选路径
        if os.path.isfile(candidate):
            yield os.path.abspath(candidate) #用生成器可以方便控制返回的数据.可以使用.next()等方法只返回下一个子项
def parse_args():#帮助提示
    usage = u'''这是一个查找文件夹路径中是否有文件指定文件的脚本,
第一个参数是要找的文件名,第二个是路径'''
    parser = optparse.OptionParser(usage)
    help = u'要查找的文件名字'
    parser.add_option('--filename', help=help)#type='int',
    help = u'查找的路径多个路径以;分隔'
    parser.add_option('--path', help=help, default='e:')
    options, args = parser.parse_args()
    return options, args
if __name__ == '__main__':
    options, args = parse_args()
    find_file = list(search_file(args[0], args[1]))
    if find_file:
        for file in find_file:
            print "Found File at %s" % file
    else:
        print "Not Found"

 
例子:在e:/py和e:/phpwww目录下找以a到d开头的.php的文件
E:py>python_cook [a-d]*.php e:/py;e:/phpwww
2 match
e:/phpwwwcurl.php
e:/phpwwwduoxiancheng.php

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python微信公众号开发平台

Python微信公众号开发平台

  上大学的时候,对微信公众号开发浅尝辄止的玩了一下,感觉还是挺有意思的。 /post/133677.htm后来服务器到期了,也就搁置了。由于发布web程序,使用PHP很顺手,...

Python实现Sqlite将字段当做索引进行查询的方法

本文实例讲述了Python实现Sqlite将字段当做索引进行查询的方法。分享给大家供大家参考,具体如下: 默认从sqlite中获取到的数据是数字索引的, 在开发阶段经常有修改数据库所以显...

python实现在windows下操作word的方法

本文实例讲述了python实现在windows下操作word的方法。分享给大家供大家参考。具体实现方法如下: import win32com from win32com.client...

Python数据分析之真实IP请求Pandas详解

前言 pandas 是基于 Numpy 构建的含有更高级数据结构和工具的数据分析包类似于 Numpy 的核心是 ndarray,pandas 也是围绕着 Series 和 DataFra...

网易2016研发工程师编程题 奖学金(python)

本文为大家分享了网易2016研发工程师编程题,供大家参考,具体内容如下 ''' [编程题] 奖学金 时间限制:1秒 空间限制:32768K 小v今年有n门课,每门都有考试,为了拿到奖学金...