[問題] 排除os.walk中的「路徑」
簡單來說
在使用os.walk的時候
有些子目錄是不想讀取要排除的
目前有找到兩個方法
第一種
import os
for root, dirs, files in os.walk(a):
if '目錄名稱' in dirs:
dirs.remove('目錄名稱')
第二種
import os
exclude = set([目錄名稱])
for root, dirs, files in os.walk(top, topdown=True):
dirs[:] = [d for d in dirs if d not in exclude]
第二種最後一行不懂那個dirs[:]和d為什麼在for前面 雖然沒有就無法執行...
這兩種原理都相同都是對dirs進行修改
藉此讓os.walk不找排除的目錄
但我發現一個問題
假設目錄列表是這樣
root--
|
---1
|
---2
|
---3---
|
---1
|
---2
我想要排除root---3---2所以輸入2的時候
他會連同root---2一起排除
所以我想要排除的是路徑
不是名稱
有什麼函數嗎
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.224.166.100 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1565029395.A.7C3.html
推
08/06 07:06,
6年前
, 1F
08/06 07:06, 1F
→
08/06 07:06,
6年前
, 2F
08/06 07:06, 2F
→
08/06 07:06,
6年前
, 3F
08/06 07:06, 3F
→
08/06 07:06,
6年前
, 4F
08/06 07:06, 4F
→
08/06 10:08,
6年前
, 5F
08/06 10:08, 5F
→
08/06 10:08,
6年前
, 6F
08/06 10:08, 6F
→
08/06 11:33,
6年前
, 7F
08/06 11:33, 7F
→
08/06 12:00,
6年前
, 8F
08/06 12:00, 8F
→
08/06 12:00,
6年前
, 9F
08/06 12:00, 9F
→
08/06 12:01,
6年前
, 10F
08/06 12:01, 10F
→
08/06 13:20,
6年前
, 11F
08/06 13:20, 11F
→
08/06 13:32,
6年前
, 12F
08/06 13:32, 12F
→
08/06 13:33,
6年前
, 13F
08/06 13:33, 13F
→
08/06 13:33,
6年前
, 14F
08/06 13:33, 14F
→
08/06 20:15,
6年前
, 15F
08/06 20:15, 15F
import fnmatch
import os
import re
excludes = ['']
excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'
for root, dirs, files in os.walk('D:\long\Desktop\image'):
dirs[:] = [os.path.join(root, d) for d in dirs]
dirs[:] = [d for d in dirs if not re.match(excludes, d)]
print(dirs)
成功運轉
接下來是想搞懂代碼是什麼意思
感謝froce告知那條奇特的函數是
list comprehension
想問一下
r'|'
r'$.'
這兩個是出自哪個函數
搜尋不了
r印象中是讀取檔案
但是讀取這兩個是什麼意思?
※ 編輯: s4028600 (125.224.166.100 臺灣), 08/06/2019 21:20:08
推
08/06 22:34,
6年前
, 16F
08/06 22:34, 16F
→
08/06 22:34,
6年前
, 17F
08/06 22:34, 17F
→
08/07 00:26,
6年前
, 18F
08/07 00:26, 18F
推
08/07 09:39,
6年前
, 19F
08/07 09:39, 19F
→
08/07 09:39,
6年前
, 20F
08/07 09:39, 20F
→
08/07 09:48,
6年前
, 21F
08/07 09:48, 21F
→
08/09 00:02,
5年前
, 22F
08/09 00:02, 22F
→
08/09 00:02,
5年前
, 23F
08/09 00:02, 23F
→
08/09 00:02,
5年前
, 24F
08/09 00:02, 24F
→
08/09 00:12,
5年前
, 25F
08/09 00:12, 25F
→
08/09 00:12,
5年前
, 26F
08/09 00:12, 26F
→
08/09 00:12,
5年前
, 27F
08/09 00:12, 27F
Python 近期熱門文章
PTT數位生活區 即時熱門文章