[英]Why python glob.glob does not give me the files I want with the regex I passed in?
例如:
20190108JPYUSDabced.csv
20190107JPYUSDabced.csv
20190106JPYUSDabced.csv
當我從終端搜索前兩個文件時:
bash: ls /Users/Downloads/201901{08,07}JPYUSDabced.csv
it gives me the first 2 files (exclude 20190106JPYUSDabced.csv)
當我在python中執行以下操作時:
import glob
glob.glob('/Users/Downloads/201901{08,07}JPYUSDabced.csv')
it gives me []
根據glob
模塊的文檔,引擎蓋glob
使用fnmatch.fnmatch
。 fnmatch
文檔描述的唯一模式是:
Pattern | Meaning --------- | ----------------------------- * | matches everything ? | matches any single character [seq] | matches any character in seq [!seq] | matches any character not in seq
對於文字匹配,請將元字符括在方括號中。 例如,“ [?]”與字符“?”匹配。
嘗試在方括號中使用字符序列:
glob.glob('/Users/Downloads/2019010[87]JPYUSDabced.csv')
假設您要搜索特定的日期范圍,則可能需要嘗試使用帶有re
表達式的os.walk
來獲取要查找的更復雜的模式。
警告: os.walk
從起始位置遞歸遍歷每個目錄,這可能不是您想要的。
無論您遇到什么情況,都必須調整正則表達式,但這是一個示例:
正則表達式匹配日期20181208
或日期20190107
但必須包含標識符JPYUSDabced.csv
。
regex = re.compile("(?:(?:20181208)|(?:20190107))JPYUSDabced.csv")
files = []
for dirpath, dirnames, filenames in os.walk('/Users/Downloads'):
for f in filenames:
if regex.match(f):
files.append(os.path.join(dirpath, f))
print(files)
# ['/Users/Downloads/20190107JPYUSDabced.csv', '/Users/Downloads/20181208JPYUSDabced.csv']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.