【问题标题】:How do I get some(5) list of files in a directory and subfolders in Python?如何在 Python 中的目录和子文件夹中获取一些(5)文件列表?
【发布时间】:2019-09-16 10:13:49
【问题描述】:

如何在 Python 中获取目录和子文件夹中的一些文件列表? 我只想在每个目录中获取 5 个 .txt 文件。

我已经搜索了很多,但找不到答案。

需要你的帮助。

我一直在测试 Path、glob、os.walk()。

import os
    for files in Path(".").glob(extension):
        print(files)

打印所有带有扩展名的文件列表

import os
    cpt = sum([len(files) for r, d, files in os.walk(".")])
    cpt = [len(files) for r, d, files in os.walk(dpath)]
    print(cpt)

[5, 25, 3, 0, 0, 1, 2, 2, 0, 0, 0, 8, 8, 4, 16, 4, 8]

现在所有文件,但每个目录中有 5 个文件。

【问题讨论】:

  • 因为不太明白,多解释一下。
  • 切片文件最多五个,你遇到什么错误?
  • 这不是你想要的吗?
  • 哦,还有txt要求,我忘记了抱歉

标签: python recursion file-extension


【解决方案1】:

dir_path开始获取recursively5 x .txt files

import os

for root, dirs, files in os.walk(dir_path):
    count = 0
    for file in files:
        if file.endswith(".txt"):
            print(os.path.join(root, file))
            count += 1
            if count == 5:
                break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多