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

标签 python python-2.7

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

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

相关文章:

python - 如何使用python仅为特定列组合创建相关矩阵?

python - 在 Python 中使用代理命令连接到 SFTP 客户端

Python 2.7.x 压缩文件 : slow unzip from network drive (Windows)

python - 使用 python 下载 .csv 文件

python - beautifulSoup html csv

Python:如何将使用 MIME 生成的电子邮件保存到磁盘

python - 将使用 lambda 的字符串连接转换为 f 字符串

Python Selenium 发送键给出大小警告

python - windows 10下安排python脚本加载数据到BigQuery

database - 恢复程序的最后状态