【问题标题】:Listing files and folders recursively in Python在 Python 中递归列出文件和文件夹
【发布时间】:2021-03-21 17:39:07
【问题描述】:

具有如下树结构:

custom_test/
├── 110/
│   ├── 1548785454_CO_[1].txt
├── 120/
│   ├── 1628785454_C4_[1].txt
└── 13031/
│   ├── 1544725454_C2_[1].txt
└── test_results/
│   ├── resulset1.txt
│   ├── hey.txt
script.py <------- this is the script which runs the Python code

我想获取除test_results 之外的所有文件夹的文件和子文件夹(我想忽略此文件夹)。使用上面的缩小示例,我想要的输出是:

['110\\1548785454_CO_[1].txt', '120\\1628785454_C4_[1].txt', '13031\\1544725454_C2_[1].txt']

这是我的尝试,它产生了输出,但它也包括 test_results 文件夹中的那些:

deploy_test_path = "custom_test"
    print([os.path.join(os.path.basename(os.path.relpath(os.path.join(filename, os.pardir))), os.path.basename(filename)) for filename in glob.iglob(deploy_test_path + '**/**', recursive=True) if os.path.isfile(filename)])

没有列表理解(为了更容易理解):

deploy_test_path = "custom_test"
for filename in glob.iglob(deploy_test_path + '**/**', recursive=True):
    if os.path.isfile(filename):
        a = os.path.join(os.path.basename(os.path.relpath(os.path.join(filename, os.pardir))), os.path.basename(filename))
        print(a)

如何归档我的目标?我知道我可以从数组中删除 test_results 的元素,但是还有更优雅和 Pythonic 的等待这样做吗?

提前致谢

【问题讨论】:

  • 使用glob.iglob('custom_test/**[!test_results]/**', recursive=True): 这将排除test_result 文件夹(仅用于第一级)。另请参阅 this 帖子,其中显示了排除规则以及如何使用集合来排除两种不同的模式。

标签: python python-3.x file directory list-comprehension


【解决方案1】:

每当我需要操纵路径时,我都会求助于Pathlib

以下是我的做法,或多或少:

from pathlib import Path

dir = Path("custom_test")
files = dir.rglob("*")
res = [f.relative_to(dir) for f in files if not f.match("test_results/*")]

单行:

from pathlib import Path

res = [f.relative_to("custom_test") for f in Path("custom_test").rglob("*") if not f.match("test_results/*")]

如果你只需要文件,你可以使用rglob("*.*"),或者

dir = Path("custom_test")
res = [f.relative_to(dir) for f in dir.rglob("*") if not f.match("test_results/*") and f.is_file()]

【讨论】:

  • 这也包括目录。我只想获取文件。
  • 它还包括输出中的custom_test。请查看帖子的所需输出。
  • 请检查我的第二条评论!
  • 好的,然后检查我的第二个编辑 ;-) 并随意阅读 Pathlib 文档,它非常强大!
  • 我的代码仍然没有得到正确的输出。它输出文件夹。这个有效:res = [str(f.relative_to(*f.parts[:1])) for f in Path("custom_test").rglob("*") if not f.match("test_results/*") and f.is_file()]
【解决方案2】:

我遇到了同样的情况,做了以下事情:

import os

IGNORE_FOLDERS = ("test_results",".git")` #as many folders as you need to ignore


    def get_data():
        root, dirnames, filenames = next(os.walk(file_path))
        for dirname in (d for d in dirnames if d not in IGNORE_FOLDERS):
            print(filenames) # or save them to a variable if you like

    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多