gpt4 book ai didi

python - 仅枚举具有特定名称的文件夹中的文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:39 25 4
gpt4 key购买 nike

我有这样的文件夹结构和文件:

 - 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.

我只想枚举每个主文件夹中 inboxsent 文件夹中的文件。我知道如何像这样枚举所有文件:

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

但这仍然只是枚举所有文件。如何枚举指定文件夹名称的文件夹中的文件?

最佳答案

您混淆了 rootdirsroot 是每一级的“当前目录”; 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

关于python - 仅枚举具有特定名称的文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26872608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com