[英]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:打破这个:
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.