![](/img/trans.png)
[英]How do I extract specified matches using regular expression in Python?
[英]How do I search through a folder for the filename that matches a regular expression using Python?
我在編寫一個函數時遇到一些困難,該函數將在目錄中搜索與特定正則表達式匹配的文件(我使用're.compile'編譯)。 所以我的問題是:如何搜索目錄(我計划使用os.walk)來查找與特定正則表達式匹配的文件? 非常感謝一個例子。 提前致謝。
這將找到所有以兩位數字開頭並以gif結尾的文件,如果您願意,可以將文件添加到全局列表中:
import re
import os
r = re.compile(r'\d{2}.+gif$')
for root, dirs, files in os.walk('/home/vinko'):
l = [os.path.join(root,x) for x in files if r.match(x)]
if l: print l #Or append to a global list, whatever
閱讀RE模式的match
方法。
選擇一個使用fnmatch
。 用re.match
替換fnmatch
。 這需要仔細考慮。 這不是剪切和粘貼。
然后,提出具體問題。
如果你必須匹配的模式很簡單,可以使用文件系統通配符,我建議你看一下glob模塊,它就是為了這個目的而存在的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.