【问题标题】:Python, I want to find file each subfolder on a folderPython,我想在文件夹中的每个子文件夹中查找文件
【发布时间】:2017-12-11 09:22:26
【问题描述】:

例子:

>>> path = ('datasets/subfolder 1/')
>>> pth = os.listdir(path)
>>> file = pth
>>> while True:
...     for file in pth:
...         print(file)
...     break
>>> 1.jpg, 2.jpg

文件夹

  • 子文件夹 1
  • 子文件夹 2
  • 子文件夹 3

我想在 python 中的子文件夹 2 和子文件夹 3 旁边的子文件夹 1 中查找文件 我需要得到完整的路径:

/home/pi/Desktop/datasets/subfolder 1/file jpg
/home/pi/Desktop/datasets/subfolder 2/file jpg
/home/pi/Desktop/datasets/subfolder 3/file jpg

谢谢。

【问题讨论】:

  • 请向我们提供您迄今为止尝试过的代码示例。这样我们就可以更有效地帮助您。
  • 这还不够详细。请编辑并改写。
  • path = ('datasets/data/') pth = os.listdir(path) file = pth while True: for file in pth: print(file) break
  • import os x = [i[2] for i in os.walk('.')] y=[] i=0 for t in x: for f in t: y.append( f) while i
  • 嘿@Chatchai.J 答案对你有用吗?

标签: python python-3.x python-2.7


【解决方案1】:

假设您不希望在树中进一步向下,最简单的方法是:

import os

filepaths = []
iterdir = os.scandir(path_of_target_dir)
for entry in iterdir:
    filepaths.append(entry.path)

更新: 列表推导式更快更紧凑:(强烈推荐)

import os

iterdir = os.scandir(path_of_target_dir)
filepaths = [entry.path for entry in iterdir]

如果您希望按扩展名过滤:

import os

iterdir = os.scandir(path_of_target_dir)
filepaths = [entry.path for entry in iterdir if entry.name.split('.')[-1] =='jpg']  # if you only want jpg files.

如果您希望按多个扩展名进行过滤:

import os

iterdir = os.scandir(path_of_target_dir)
filepaths = [entry.path for entry in iterdir if entry.name.split('.')[-1] in {'jpg', 'docx'}]  # if you only want jpg and docx files.

...或使其更易于阅读和修改并添加排除过滤器:

import os

incl_ext = {'jpg', 'docx'}  # set of extensions; paths to files with these extensions will be collected.
excl_ext = {'txt', 'bmp'}  # set of extensions; paths to files with these extensions will NOT be collected.

get_ext = lambda file: file.name.split('.')[-1]  # lambda function to get the file extension.
iterdir = os.scandir(path_of_target_dir)
filepaths = [entry.path for entry in iterdir if get_ext(entry) in incl_ext and get_ext(entry) not in excl_ext]
print(filepaths)

你可以把它变成一个函数。 (你应该把它变成一个函数)。

【讨论】:

    猜你喜欢
    • 2020-11-05
    • 2019-10-18
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    相关资源
    最近更新 更多