''' 在python中,glob模塊是用來查找匹配的文件的 在查找的條件中,需要用到Unix shell中的匹配規則: * : 匹配所所有 ? : 匹配一個字符 *.* : 匹配如:[hello.txt,cat.xls,xxx234s.doc] ?.* : 匹配如:[1.txt,h.py] ?.gif: 匹配如:[x.gif,2.gif] 可以參考:fnmatch 如果沒有匹配的,glob.glob(path)將返回一個空的list:[] '''
以下是我的demo
運行效果:
=============================================
代碼部分:
=============================================
1 #python glob 2 3 ''' 4 在python中,glob模塊是用來查找匹配的文件的 5 在查找的條件中,需要用到Unix shell中的匹配規則: 6 7 * : 匹配所所有 8 ? : 匹配一個字符 9 *.* : 匹配如:[hello.txt,cat.xls,xxx234s.doc] 10 ?.* : 匹配如:[1.txt,h.py] 11 ?.gif: 匹配如:[x.gif,2.gif] 12 13 如果沒有匹配的,glob.glob(path)將返回一個空的list:[] 14 ''' 15 import glob 16 17 def get_all(): 18 '''獲取目錄[c:\\tmp]下面所有的文件''' 19 return glob.glob('c:\\tmp\\*.*') 20 21 def get_my_file(): 22 '''獲取目錄[c:\\tmp]下面文件名為4個字符的文件''' 23 return glob.glob('c:\\tmp\\????.txt') 24 25 def get_batch_file(): 26 '''獲取目錄[c:\\tmp]下面擴展名為\'.txt\'的文件''' 27 return glob.glob('c:\\tmp\\*.txt') 28 29 def main(): 30 print('獲取目錄[c:\\tmp]下面所有的文件:') 31 tem_files = get_all() 32 print(tem_files) 33 print('獲取目錄[c:\\tmp]下面文件名為4個字符的文件:') 34 tem_files = get_my_file() 35 print(tem_files) 36 print('獲取目錄[c:\\tmp]下面擴展名為\'.txt\'的文件:') 37 tem_files = get_batch_file() 38 print(tem_files) 39 40 if __name__ == '__main__': 41 main()
========================================================
More reading,and english is important.
I'm Hongten
大哥哥大姐姐,覺得有用打賞點哦!多多少少沒關系,一分也是對我的支持和鼓勵。謝謝。
Hongten博客排名在100名以內。粉絲過千。
Hongten出品,必是精品。
E | hongtenzone@foxmail.com B | http://www.cnblogs.com/hongten
========================================================