如何扫描目录中的文件夹并获取末尾编号最高的文件夹-python

问题描述

我对 python 真的很陌生,我正在尝试自动化程序。 我有一些文件夹,我想输入末尾编号最高的文件夹。in the picture i have some folders. and i want to take the folder with the highest number at the end. for example in this picture,folder_4 这是我到目前为止所尝试的。我不知道如何继续,或者我的代码是否有效。

import os
import shutil
import glob

path="N:\QA\Automation\Projects\AT_Projects"
projectlist = os.listdir(path)
for project in projectlist:
    projectdir = path + "\\" + project
    file_path=[]
    print(projectlist)
 
    if os.path.isdir(projectdir):
        folders=os.listdir(projectdir)
        for folder in folders:
            file_path=folder
        
      
            if os.folderdir.isdir(folder):
            
               print('true')

   
    else:
        print("done")

我想扫描文件夹,最后输入 folder_4 从中获取一些东西。

我如何进行此扫描?

解决方法

假设所有内容都在同一个文件夹中,您可以执行以下操作:

from pathlib import Path

p = Path.cwd()  # Alternatively,use Path(<your folder path>) to point to another folder
sorted_folders = list(sorted(p.glob("*[0-9]/"),key=lambda x: int(x.name.split("_")[-1])))

这适用于包含要作为排序依据的文件夹的文件夹。

分解:

  1. 使用 pathlib.Path 可以获得当前工作目录的 Path 对象
  2. 将 Path.glob 与模式“*[0-9]/”一起使用,它为您提供目录(所有文件夹)中以数字结尾的所有内容的生成器
  3. 使用 sorted,键是“在 _ 上拆分名称并取该名称的最后一部分”,例如“文件夹_1”-> [“文件夹”,“1”]。我们应用 int 以便将这里的最后一个元素视为数字,而不是字符串
  4. 创建一个列表,以便按顺序排列文件夹

如果你想要数量最多的文件夹,你可以取你列表的最后一个成员

sorted_folders[-1]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...