glob

python3 glob模塊
python官網解釋

  • glob模塊根據Unix shell使用的規則查找與指定模式匹配的所有路徑名,儘管結果以任意順序返回。用它可以查找符合特定規則的文件路徑名
  • 查找文件只用到三個匹配符:"*", “?”, “[]”。
    • “*” 匹配0個或多個字符
    • “?” 匹配單個字符
    • “[]” 匹配指定範圍內的字符
    • 如果沒有匹配的,glob.glob(path)將返回一個空的列表[]
  • 包括
    • glob.glob(pathname, *, recursive=False)
    • glob.iglob(pathname, recursive=False)
    • glob.escape(pathname)
  • glob.glob()示例
  1. glob.py
import glob
def get_all():
    '''獲取目錄'D:/spyder_project/exercise'下面所有的文件'''
    return glob.glob('D:/spyder_project/exercise/*')

def get_my_file():
    '''獲取目錄'D:/spyder_project/exercise'下面文件名爲4個字符的文件'''
    return glob.glob('D:/spyder_project/exercise/????.txt')

def get_batch_file():
    '''獲取目錄'D:/spyder_project/exercise'下面擴展名爲'.txt'的文件'''
    return glob.glob('D:/spyder_project/exercise/*.txt')

def main():
    print('獲取目錄D:/spyder_project/exercise下面所有的文件:')
    tem_files = get_all()
    print(tem_files)
    print('獲取目錄D:/spyder_project/exercise下面文件名爲4個字符的文件:')
    tem_files = get_my_file()
    print(tem_files)
    print('獲取目錄D:/spyder_project/exercise下面擴展名爲.txt的文件:')
    tem_files = get_batch_file()
    print(tem_files)

if __name__ == '__main__':
    main()
  1. 目錄D:/spyder_project/exercise文件如下
    在這裏插入圖片描述
  2. 結果
獲取目錄D:/spyder_project/exercise下面所有的文件:
['D:/spyder_project/exercise\\a.png.jpg', 'D:/spyder_project/exercise\\b.txt.txt', 'D:/spyder_project/exercise\\cccc.txt.txt', 'D:/spyder_project/exercise\\yq.doc.doc']
獲取目錄D:/spyder_project/exercise下面文件名爲4個字符的文件:
[]
獲取目錄D:/spyder_project/exercise下面擴展名爲.txt的文件:
['D:/spyder_project/exercise\\b.txt.txt', 'D:/spyder_project/exercise\\cccc.txt.txt']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章