获取包含文件的子文件夹路径的最有效方法是什么。例如,如果这是我的输入结构。
inputFolder
│
└───subFolder1
│ │
│ └───subfolder11
│ │ file1.jpg
│ │ file2.jpg
│ │ ...
│
└───folder2
│ file021.jpg
│ file022.jpg
如果我通过getFolders(inputPath)
,
它应该将输出作为包含图像的文件夹列表返回 ['inputFolder/subFolder1/subFolder11','inputFolder/folder2']
目前我正在使用我的库 TreeHandler ,它只是 os.walk 的包装器,用于获取所有文件。
import os
from treeHandler import treeHandler
th=treeHandler()
tempImageList=th.getFiles(path,['jpg'])
### basically tempImageList will be list of path of all files with '.jpg' extension
### now is the filtering part,the line which requires optimisation.
subFolderList=list(set(list(map(lambda x:os.path.join(*x.split('/')[:-1]),tempImageList))))
我认为可以更有效地完成。
提前致谢
最佳答案
- 分割路径的所有部分并重新连接它们似乎会降低效率。
查找“/”最后一个实例的索引并进行切片的速度要快得多。
def remove_tail(path): index = path.rfind('/') # returns index of last appearance of '/' or -1 if not present return (path[:index] if index != -1 else '.') # return . for parent directory . . . subFolderList = list(set([remove_tail(path) for path in tempImageList]))
已在 AWA2 数据集文件夹(50 个文件夹和 37,322 个图像)上进行验证。
- 观察到的结果快了约 3 倍。
- 使用列表理解增强了可读性。
- 处理了父目录包含图像的情况(这会导致现有实现出现错误)
添加用于验证的代码
import os
from treeHandler import treeHandler
import time
def remove_tail(path):
index = path.rfind('/')
return (path[:index] if index != -1 else '.')
th=treeHandler()
tempImageList= th.getFiles('JPEGImages',['jpg'])
tempImageList = tempImageList
### basically tempImageList will be list of path of all files with '.jpg' extension
### now is the filtering part,the line which requires optimisation.
print(len(tempImageList))
start = time.time()
originalSubFolderList=list(set(list(map(lambda x:os.path.join(*x.split('/')[:-1]),tempImageList))))
print("Current method takes", time.time() - start)
start = time.time()
newSubFolderList = list(set([remove_tail(path) for path in tempImageList]))
print("New method takes", time.time() - start)
print("Is outputs matching: ", originalSubFolderList == newSubFolderList)
关于python - 查找包含图像的子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61207834/