Although I have files in the directory, the code is not returning anything, can anyone help me?
from pathlib import Path
date_creation = lambda f: f.stat().st_ctime
directory = Path('directory')
files = directory.glob('*.py')
sorted_files = sorted(files, key = date_creation, reverse = True)
for f in sorted_files:
print(f)
Note that the argument that you pass to Path()
is being interpreted as a relative path, rather than as an absolute path.
This means that, at the time of running this code, you will be looking for a sub-directory called 'directory', within whatever happens to be the current directory.
Based on this understanding, please pass the correct argument to Path()
. That should get you the results.
For example, on my machine, the following code that uses an absolute path works fine:
from pathlib import Path
date_creation = lambda f: f.stat().st_ctime
directory = Path('F:/MyParentFolder/MySubFolder')
files = directory.glob('*.py')
sorted_files = sorted(files, key = date_creation, reverse = True)
for f in sorted_files:
print(f)