简体   繁体   English

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

[英]how to scan folders in directory and get the folder with the highest number at the end -python

i am really new to python and i am trying to automate procedure.我对 python 真的很陌生,我正在尝试自动化程序。 i have some folders and i want to enter the folder with the highest number at the end.我有一些文件夹,我想在末尾输入数字最高的文件夹。 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 this is what i tried so far.例如在这张图片中,folder_4这是我到目前为止所尝试的。 i do not know how to continue or if my code is any effective.我不知道如何继续,或者我的代码是否有效。

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")

I want to scan the folder and at the end enter folder_4 to get something from it.我想扫描文件夹,最后输入 folder_4 从中获取一些东西。

how do I do this scan?我怎么做这个扫描?

Assuming everything is in the same folder, you can do something like this:假设所有内容都在同一个文件夹中,您可以执行以下操作:

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])))

This works from the folder containing the folders you want to sort by.这适用于包含要排序的文件夹的文件夹。

Breaking this down:打破这个:

  1. Using pathlib.Path you get a Path object for the current working directory使用 pathlib.Path 可以获得当前工作目录的 Path 对象
  2. Use Path.glob with the pattern "*[0-9]/", which gives you a generator for everything in the directory (all your folders) that end with a number将 Path.glob 与模式“*[0-9]/”一起使用,它为您提供目录(所有文件夹)中以数字结尾的所有内容的生成器
  3. Use sorted, with a key that is "split the name on _ an take the last piece of that name", eg "folder_1" -> ["folder", "1"].使用 sorted,键是“在 _ 上拆分名称并取该名称的最后一部分”,例如“folder_1”-> [“folder”,“1”]。 We apply int so that the last element here is treated as a number, not a string我们应用 int 以便将这里的最后一个元素视为数字,而不是字符串
  4. create a list so that you have the folders in order创建一个列表,以便按顺序排列文件夹

If you then want the folder with the largest number, you can take the last member of your list如果您想要具有最大编号的文件夹,则可以采用列表中的最后一个成员

sorted_folders[-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM