Jayank
Jayank

Reputation: 91

Last modified sub directory using python

I am trying to pull list of all latest modified sub folders in directory, using python. Test is master path, which contains two sub folder 1 and 2. Folder 1 contains folder 101 and 102, folder 2 contains folder 201 and 202. I tried below code but not giving me desired output. Please support with guidance.

MasterPath = r'Z:\Jayank\test\\'
FolderNum = ['1','2']
SubPath = []
TargetPath = []

for n in FolderNum:
    for i in os.scandir(MasterPath + n + '\\'):
        SubPath.append(i.path)
        Tp = max(SubPath, key = os.path.getmtime)
        TargetPath.append(Tp)

print(TargetPath)

Upvotes: 0

Views: 382

Answers (1)

munir.aygun
munir.aygun

Reputation: 442

You have to determine subpaths first, then find latest modified file. So only thing you need to do is put this line Tp = max(SubPath, key = os.path.getmtime) out of for loop. But I think you should use os.walk for listing sub directories. os.walk scans sub directories recursively. Check this script:

sub_paths = list() # Collect all files in sub directories
for root, dirs, files in os.walk(<your_path>):
    sub_paths += [os.path.join(root,i) for i in files]
 
print(max(sub_paths,key=os.path.getmtime))

Upvotes: 1

Related Questions