glob模塊
- 1.glob.glob()
- 2.對比os.listdir()
glob是python自帶的一個操作文件的模塊,可用于查找 指定路徑 中 匹配的 文件。
1.glob.glob()
下面是一個測試文件路徑:
(base) pp@pp-System-Product-Name:~/Desktop/test_glob$ tree
.
├── a
│ ├── 12.txt
│ ├── 1.txt
│ └── 2.txt
└── b├── 12.txt├── 1.txt└── 2.txt2 directories, 6 files
使用glob查找 匹配的路徑(返回符合模糊匹配規則的文件路徑):
import glob
>>> glob.glob("/home/pp/Desktop/test_glob/a/1*") # *用于匹配任意字符['/home/pp/Desktop/test_glob/a/12.txt', '/home/pp/Desktop/test_glob/a/1.txt']
模糊匹配符:
”*”匹配0個或多個字符;”?”匹配單個字符;”[]”匹配指定范圍內的字符,如:[0-9]匹配數字。
參考資料:https://blog.csdn.net/gufenchen/article/details/90723418
2.對比os.listdir()
–只是列出給定路徑中的 文件或目錄名:
>>> import os
>>> os.listdir("/home/pp/Desktop/test_glob/a")['2.txt', '12.txt', '1.txt']>>> os.listdir("/home/pp/Desktop/test_glob")
['a', 'b']