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 ' % 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实现在目录中查找指定文件的方法的更多相关文章

  1. 在eclipse中查找指定文件 [多种方法]

    在eclipse中查找指定文件   1.ctrl+h打开搜索界面 File Search: containing text填*,File name patterns填写hello.*,可以找到hell ...

  2. 在eclipse中查找指定文件

    1.ctrl+h打开搜索界面 File Search: containing text填*,File name patterns填写hello.*,可以找到hello为命名的文件 知道文件类型,查找里 ...

  3. 在eclipse中如何在大量项目中查找指定文件

    在eclipse中如果希望在大量的项目中寻找指定的文件可不是一件轻松的事,还好eclipse提供了强大的搜索功能. 我们可以通过通配符或正则表达式来设定查寻条件,下面是操作示例: ctrl+h 打开搜 ...

  4. 在eclipse中如何在大量项目中查找指定文件(转载)

    转载:http://blog.csdn.net/inowcome/article/details/6699227 在eclipse中如果希望在大量的项目中寻找指定的文件可不是一件轻松的事,还好ecli ...

  5. python从一个目录中复制全部文件图片至另一个目录中,及删除指定目录中的图片

    import shutil import os #目录自己改一下即可,复制 path = "./static/imgs/" new_path = "./static/up ...

  6. python在一堆目录中寻找json文件

    在一个目录下,有好几层目录,里面零零散散存放着几个json文件,我要做的是用python脚本把它们都找出来,一开始就一层一层地找,用os.listdir加上for循环,根据目录树的深度确定for循环的 ...

  7. QT中检索设定目录下所有指定文件的方法

    void MainWindow::on_pushButton_clicked() { QDir dir=QFileDialog::getExistingDirectory(this, tr(" ...

  8. File类之在指定目录中查找文件

    package IoDemo; import java.io.File; /** * @Title:FileDemo2 * @Description:在指定的目录中查找文件 * @author Cra ...

  9. Linux find查找指定文件 按照名称 然后cp拷贝到指定目录且指定文件名

    最近有一个需求,需要将指定目录下的文件(已知文件名)复制到另一个指定的目录且重命名文件. 要求: 在var目录下会定义系统的启动日志相关信息,请查找对应的boot.log文件,并把它备份一份到var/ ...

随机推荐

  1. Educational Codeforces Round 40 G. Castle Defense (二分+滑动数组+greedy)

    G. Castle Defense time limit per test 1.5 seconds memory limit per test 256 megabytes input standard ...

  2. python Pillow 图片处理模块,好强大有没有

    python Pillow 图片处理模块,好强大有没有 Pillow 需要给 python 另外安装 第一个用法:https://www.cnblogs.com/ibingshan/p/1105739 ...

  3. HTML5——5 HTML5 SVG

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. MyBatis-12-动态SQL

    12.动态SQL 什么事动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句 利用动态SQL这一特性可以彻底摆脱这种痛苦 动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似 ...

  5. C# ado.net 操作存储过程(二)

    调用存储过程 sql IF OBJECT_ID('RegionInsert') IS NULL EXEC (' -- -- Procedure which inserts a region recor ...

  6. Linux查找文件内容小技巧

    目录 grep ag linux系统查找文件内容最常见的命令有grep和ag grep grep是比较常见的查找命令 # 在当前目录的py文件里查找所有相关内容 grep -a "broad ...

  7. laravel Passport - Dingo/Api v2.0+Passport 实现 api 认证

    第一部分: 安装passport 使⽤ Composer 依赖包管理器安装 Passport : composer require laravel/passport 接下来,将 Passport 的服 ...

  8. Crystal Report中文顯示亂碼

    1.首先要確定該中文字體在OS裏有沒有安裝 C:\WINDOWS\Fonts 這個folder下沒有找到的話就從別的機器拷貝ttf字體文件,然後 File -> Install New Font ...

  9. Combine String HDU - 5707 dp or 广搜

    Combine String HDU - 5707 题目大意:给你三个串a,b,c,问a和b是不是恰好能组成c,也就是a,b是不是c的两个互补的子序列. 根据题意就可以知道对于c的第一个就应该是a第一 ...

  10. Codevs 3012 线段覆盖 4

    3012 线段覆盖 4 时间限制: 1 s 空间限制: 64000 KB 题目等级 : 黄金 Gold 题目描述 Description 数轴上有n条线段,线段的两端都是整数坐标,坐标范围在0~100 ...