Python list files in directory (All Methods Each With Code)

WHAT IS A DIRECTORY?

A directory, also known as a folder, is a container in a file system that can hold files and other directories. Directories can be used to organize and structure files on a computer’s file system.

PYTHON LIST FILES IN A DIRECTORY(Methods):

OS MODULE:

The os module in Python provides a way to interact with the underlying operating system. It can be used to list the files in a directory using the listdir() function.

EXAMPLE :

import os
path = '/path/to/dir'
files = os.listdir(path)
print(files)

OS.WALK():

The os.walk() function generates the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

EXAMPLE:

import os

for root, dirs, files in os.walk("/path/to/dir"):
    for file in files:
        print(os.path.join(root, file))

GLOB() METHOD:

The glob() method returns a list of files or directories that match a given pattern. This method uses the Unix shell-style wildcards (e.g. *, ?, and []).

EXAMPLE:

import glob

path = '/path/to/dir/*.txt'
files = glob.glob(path)
print(files)

IGLOB():

The iglob() function returns an iterator that generates the file names matching the specified pattern. The pattern is a Unix shell-style wildcard (e.g. *, ?, and []).

EXAMPLE:

import glob

path = '/path/to/dir/*.txt'
for file in glob.iglob(path):
    print(file)

Note: It is recommended to use iglob() over glob() as it uses less memory when working with large directories.

Leave a Comment