python list files in directory in 2 effective methods

0
646
Listing-the contained Directories with a given directory with Python
Listing the contained Directories with a given directory with Python

There are two modified ways or methods python list files in directory listdir.

also see PYTHON listing files contained in a directory which explains the detailed note in advance of using os.walker and glob with specified file type but here I described how to simply list files contained in a directory in two simple methods.

Listing Directory Using Python
Listing Directory Using Python

1st Method : python listing directory

Legacy method of Directory listing with python

import os
entries = os.listdir('shopinson/')
for entry in entries:
    print(entry)

the above python code snippets displays all files contained in the specified directory named “shopinson

2nd Method : listing directory using python

Modern method of Directory listing with python

#1 Example: 2nd Method Using os.scandir()

import os
with os.scandir('shopinson/') as entries:
    for entry in entries:
        print(entry.name)

#2 Example: 2nd Method Using pathlib.Path()

from pathlib import Path

entries = Path('shopinson/')
for entry in entries.iterdir():
    print(entry.name)

Difference between the two method is that the 1st method uses os.listdir() while the second method uses os.scandir() and pathlib.Path().

Note: to get list of file types including it types best method is the modern method

LEAVE A REPLY

Please enter your comment!
Please enter your name here