Python:glob模板

来源:互联网 发布:定金和尾款淘宝客 编辑:程序博客网 时间:2024/06/07 17:30
    在python中,glob模块是用来查找匹配的文件的
    在查找的条件中,需要用到Unix shell中的匹配规则:
       *    :   匹配所所有
       ?    :   匹配一个字符
       *.*  :   匹配如:[hello.txt,cat.xls,xxx234s.doc]
       ?.*  :   匹配如:[1.txt,h.py]
       ?.gif:   匹配如:[x.gif,2.gif]

    如果没有匹配的,glob.glob(path)将返回一个空的list:[]

#python globimport globdef get_all():    '''获取目录[c:\\Python27\\wenjian]下面所有的文件'''    return glob.glob('c:\\Python27\\wenjian\\*.*')def get_my_file():    '''获取目录[c:\\Python27\\wenjian]下面文件名为4个字符的文件'''    return glob.glob('c:\\Python27\\wenjian\\????.txt')def get_batch_file():    '''获取目录[c:\\Python27\\wenjian]下面扩展名为\'.txt\'的文件'''    return glob.glob('c:\\Python27\\wenjian\\*.txt')def main():    print('获取目录[c:\\Python27\\wenjian]下面所有的文件:')    tem_files = get_all()    print(tem_files)    print('获取目录[c:\\Python27\\wenjian]下面文件名为4个字符的文件:')    tem_files = get_my_file()    print(tem_files)    print('获取目录[c:\\Python27\\wenjian]下面扩展名为\'.txt\'的文件:')    tem_files = get_batch_file()    print(tem_files)if __name__ == '__main__':    main()
运行结果:

>>> 获取目录[c:\Python27\wenjian]下面所有的文件:['c:\\Python27\\wenjian\\1.py', 'c:\\Python27\\wenjian\\cat.py', 'c:\\Python27\\wenjian\\main.py', 'c:\\Python27\\wenjian\\mtsleep4.py', 'c:\\Python27\\wenjian\\poem.txt', 'c:\\Python27\\wenjian\\translateutil.py', 'c:\\Python27\\wenjian\\translateutil.pyc']获取目录[c:\Python27\wenjian]下面文件名为4个字符的文件:['c:\\Python27\\wenjian\\poem.txt']获取目录[c:\Python27\wenjian]下面扩展名为'.txt'的文件:['c:\\Python27\\wenjian\\poem.txt']

0 0