To list all files in a directory, we could use Path object in pasthlib module. By passing a directory name to the Path object, the result will be another object capable of generating an iterator object with which we can use for loop to get all files in that directory.

 

from pathlib import Path

basepath = Path('asset/')
files = basepath.iterdir()

for item in files:
    if item.is_file():
        print(item.name)

 

To list subdirectories instead of files, we can use Path( ) method in pathlib module.

 

from pathlib import Path

basepath = Path('asset/')
for entry in basepath.iterdir():
    if entry.is_dir():
        print(entry.name)

 

We call .is_dir( ) method on each entry of the basepath iterator to check if an entry is a file or a directory. If the entry is a directory, its name is printed out to the screen,

 

In Python, we can easily retrieve file attributes such as file size and modified times. This can be done through pathlib.Path( ) method.

 

from pathlib import Path

current_dir = Path('asset')
for path in current_dir.iterdir():
    info = path.stat()
    print(info.st_mtime)

 

In the code above, the code loops through the object returned by .iterdir( ) and retrieves file attributes through a .stat( ) call for each file in the directory list. The st_mtime attribute returns a float value that represents seconds since the epoch.