| by Arround The Web | No comments

List Files in a Directory Python

A “Directory” is a location on your file system that contains “Files” or other directories. In Python, you can work with directories using the “os” module, which provides various functions for interacting with the file system. We may encounter many situations where there is a need to list all files in a directory or subdirectory. A variety of built-in methods and libraries are available in Python that can help you analyze, process, or simply organize your data.

This article will show you how to list files in a directory using the following methods in Python with appropriate examples:

Method 1: List Files in a Directory Utilizing “os.listdir()” Function

The “os.listdir()” function retrieves all files lists and directories in the given path.

Example

Here’s how you can use the discussed function to list all files in the current directory:

import os
files = os.listdir()
for file in files:
    if os.path.isfile(file):
        print(file)

 

In the above code, the “os.listdir()” function is used along with the “os.path.isfile()” function to list all the files in the specified directory.

Output

The above output shows all files in the current/existing directory.

Method 2: List Files in a Directory Utilizing “glob.glob()” Function

The function “glob.glob()” generates a list of all the files that match/verify a given pattern.

Example

Following is an example code:

import os
import glob
files = glob.glob('*')
for file in files:
    if os.path.isfile(file):
        print(file)

 

In the above code snippet, the “glob” module is used to get a list of all files and directories in the current directory and then loops through them. It is such that if the item is a file, it prints its name.

Output

The above output verified that all files in the current directory have been displayed.

Method 3: List Files in a Directory Utilizing “os.walk()” Function

The function “os.walk()” traverses a directory tree either from the top down or from the bottom up, generating a list of file names encountered in the process.

Example

The below stated code is used to list files in a directory using “os.walk()” function:

import os
for dirpath, dirnames, filenames in os.walk('.'):
    for filename in filenames:
        print(os.path.join(dirpath, filename))

 

In the above code block, the “os.walk()” function is used to traverse the current directory, and its subdirectories, and then loops through the filenames. Based on that, all files are listed with their complete paths.

Output

This output shows all files in the present/existing directory and its subdirectories.

Method 4: List Files in a Directory Using “pathlib.Path.glob()” Method

The “pathlib.Path.glob()” method retrieves an iterator of all files that correspond to a specified pattern.

Example

The following code is used to list all the files in the specified directory:

from pathlib import Path
files = Path('.').glob('*')
for file in files:
    if file.is_file():
        print(file)

 

According to the above code:

  • The “Path” object is created for the current directory (.) and uses the “glob()” method to get an iterator of all the paths that match the pattern ‘*’ (which means any file or directory).
  • Lastly, the “for” loop loops through each path in the iterator and checks if it is a file using the “is_file()” method.

Output

Method 5: List Files in a Directory Using “scandir()” Function

The “scandir()” function is a faster and more efficient way of listing files in a directory.

Example

The following example code will list all the files in the current directory:

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

 

In the above code lines:

  • The “os” module is imported to access the operating system functions.
  • The “scandir()” function is applied that iterates over the files and directories in the current/present working directory.
  • The “is_file()” method is applied to determine whether an entry based on the applied “scandir()” function is a file.
  • If it is a file, it prints its name using the “name” attribute.

Output

As analyzed, the above output printed all files in the current directory.

Conclusion

To list files in a directory in Python, various functions such as “os.listdir()”, “glob.glob()”, “os.walk()”, “scandir()”, or the “pathlib.Path.glob()” method can be used. All of these methods are used to list all the files in a directory efficiently and quickly. These methods are explained step by step in this tutorial using numerous examples.

Share Button

Source: linuxhint.com

Leave a Reply