Python,我想在文件夹上找到每个子文件夹的文件

时间:2017-12-11 09:22:27

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

示例:

<?php
     $connect = pg_connect("host=localhost port=5432 dbname=mydb user=postgres password=mypass");
     if(!$connect)
     {
         $error = error_get_last();
         echo $error['message'];
     }
     else
     {
        echo "Connected";
     }
?>

文件夹

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

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

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

谢谢。

1 个答案:

答案 0 :(得分:0)

最简单的方法是,假设你不想在树中向下走,那就是:

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)

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