在每个子目录中查找最新的文件

2024-07-01 07:01:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似的文件夹结构,我需要从每个子目录中提取最新的.jpg:

+ C:\\myfiles
    + parentdir1
        +  subdir1
            + somename1.jpg
            + somename2.jpg
            + ...
        + subdir2
            + somename3.jpg
            + somename4.jpg
            + ...
        + ...
    + parentdir2
        +  subdir1
            + somename5.jpg
            + somename6.jpg
            + ...
        + subdir2
            + somename7.jpg
            + somename8.jpg
            + ...
        + ...
    + parentdir3
        +  subdir1
            + somename9.jpg
            + somename10.jpg
            + ...
        + subdir2
            + somename11.jpg
            + somename12.jpg
            + ...
        + ...
    + ...

我不知道任何文件夹或文件的名称,但我需要访问每个子目录中的最后2.jpg文件。你知道吗

为了简单起见,我们假设需要打印在子目录中创建的最后两个文件。你知道吗

我编写了一个脚本,可以搜索给定parentdir中的所有subdir,但实际上我也需要遍历所有parentdir

import os

path = 'C:\\myfiles'
filelist = []

for i in range(len(os.listdir(path))):
    subpath = path + '\\' + os.listdir(path)[i]
    for root, dirs, files in os.walk(subpath):
        for file in os.listdir(subpath):
            filelist.append(os.path.join(root, file))
        sorted_filelist = sorted(filelist, key=os.path.getctime)
        print('the latest jpg file in ' + root + ' is:  ' + sorted_filelist[-1])
        print('the 2nd last jpg file in ' + root + ' is:  ' + sorted_filelist[-2])
    filelist.clear()

Tags: 文件pathin文件夹forosrootfile
2条回答

我想这会满足你的要求。请注意,我按文件的上次修改时间而不是创建时间对文件进行排序,因为我认为这是确定哪些文件是“最近的”。你知道吗

import glob
import os

N_MOST_RECENT = 2
path = 'C:\\myfiles'

for entry in os.listdir(path):
    subpath = os.path.join(path, entry)
    if os.path.isdir(subpath):
        for subentry in os.listdir(subpath):
            subentrypath = os.path.abspath(os.path.join(subpath, subentry))
            if os.path.isdir(subentrypath):
                jpg_files = glob.iglob(os.path.join(subentrypath, '*.jpg'))
                sorted_filenames = sorted(jpg_files, key=os.path.getmtime)
                # Create list of filenames of the N most recent files.
                most_recent = [os.path.split(name)[-1] # Extract filename from path.
                                    for name in sorted_filenames[-N_MOST_RECENT:]]
                print(f'{N_MOST_RECENT} most recent .jpg files in "{subentrypath}":\n'
                      f'  {most_recent}')

尝试遍历父目录,然后遍历所有子目录,使用操作系统列表目录(). 你知道吗

import os

parent_dir = 'path/to/parent/dir'
for subdir in os.listdir(parent_dir):
    if not os.path.isdir(subdir):
        continue
    sorted_filelist = sorted(
        [os.path.join(parent_dir, subdir, f) for f in os.listdir(subdir)
        if os.path.splitext(f)[1] == '.jpg'],
        key=os.path.getctime, reverse=True)
    print(sorted_filelist[:2])

相关问题 更多 >

    热门问题