1

I'm trying to sort the files in a folder by the date they were created (with the most recently created first). The following commands:

import os

list1 = os.listdir(r'D:\Users\Pruthvi\Videos\Movies & TV Shows')
print(list1)

display the current files in my movies folder in an arbitrary order:

['desktop.ini', 'Friends.S05.1080p.BluRay.x264-TENEIGHTY[rartv]', 'Narcos.Mexico.S02.COMPLETE.1080p.NF.WEBRip.DDP5.1.Atmos.x264-NTG[TGx]', 'Rick.and.Morty.S04E09.1080p.WEBRip.x264-BTX[TGx]', 'South.Park.S01.1080p.BluRay.x264-SHORTBREHD[rartv]', 'Temp', 'The.Wolf.of.Wall.Street.2013.1080p.BluRay.AVC.DTS-HD.MA.5.1-SharpHD'] 

Having searched StackOverflow, the solution seems to be using the following on windows:

list1.sort(key=os.path.getctime)

However, this results in the following error:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'desktop.ini'
Pruthvi Amin
  • 75
  • 2
  • 10

1 Answers1

2

As you have seen, the os.listdir function gives you file names without any folder paths. If you pass one of these names to os.path.getctime, it won't know the folder where the file was found, so it will just look in the current folder. Unless the current folder is the same as the one passed to os.listdir, getctime will not find the same files.

So to fix it, you could make the current folder the one that supplied the file names, or you could change the list construction so the list contains complete path names rather than just file names.

Dennis Sparrow
  • 938
  • 6
  • 13