[英]Only enumerate files in folders with specific names
我有這樣的文件夾結構和文件:
- doe-john
- inbox
- 1.
- 2.
- 3.
- sent
- 1.
- 2.
- 3.
- notes
- 1.
- 2.
- 3.
- contacts
- 1.
- 2.
- 3.
- doe-jane
- inbox
- 1.
- 2.
- 3.
- sent
- 1.
- 2.
- 3.
- notes
- 1.
- 2.
- 3.
- contacts
- 1.
- 2.
- 3.
我只想枚舉每個主文件夾中inbox
和已sent
文件夾中的文件。 我知道如何枚舉所有文件,如下所示:
for root, dirs, files in os.walk(top_level_folder):
for fn in files:
with open(os.path.join(root, fn), 'r') as f:
pass # do something
我以為我會做這樣的事情,但是我不太確定如何正確地做到這一點:
for root, dirs, files in os.walk(top_level_folder):
for dir in dirs:
if dir.lower() == "inbox" or dir.lower() == "sent":
for fn in files:
with open(os.path.join(root, fn), 'r') as f:
pass # do something
但這仍然只枚舉所有文件。 如何僅枚舉具有指定文件夾名稱的文件夾中的文件?
您混淆了root
和dirs
。 root
是每個級別的“當前目錄”; dirs
是此級別上可見的 dirs
的列表 。
您當前的代碼處理每個目錄中的所有文件,每個可見子目錄一次。 您要查看當前目錄是inbox
還是sent
目錄,然后進行處理。
for root, dirs, files in os.walk(top_level_folder):
if root.lower().endswith("inbox") or root.lower().endswith("sent"):
for fn in files:
with open(os.path.join(root, fn), 'r') as f:
pass # do something
您還可以在walk
呼叫中設置topdown=True
,然后修改要進入的子目錄。
for root, dirs, files in os.walk(top_level_folder, topdown=True):
if root != top_level_folder:
# only recurse into level 3+ directories with the desired names
dirs[:] = [d for d in dirs if d in ['inbox', 'sent']]
if root.lower().endswith("inbox") or root.lower().endswith("sent"):
for fn in files:
with open(os.path.join(root, fn), 'r') as f:
pass # do something
但是,我發現該選項有點難看(特別是因為您需要在頂層使用特殊情況以避免跳過/doe-john
等)。 在您的特定情況下,由於您只想查看兩個目錄,而它們僅是下一層,因此我根本不會使用walk
:
for person in os.listdir(top_level_folder):
inbox = os.path.join(top_level_folder, person, 'inbox')
sent = os.path.join(top_level_folder, person, 'sent')
for file in os.listdir(inbox):
pass # Do something
for file in os.listdir(sent):
pass # Do something
如果使用topdown=True
選項,則可以修改os.walk()
返回的dirs
。 根據文檔 :
當自上而下為
True
,主叫方可以就地(可能使用修改dirnames中列表del
或切片分配),和walk()
將只迭代到他們的名字留在dirnames中的子目錄; 這可用於修剪搜索,強加特定的訪問順序,甚至可在調用者再次恢復walk()
之前向walk()
告知調用者創建或重命名的目錄。 修改dirnames中 ,當自上而下的False
是無效的,因為在自下而上的模式產生之前dirpath本身產生的dirnames中的目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.