Python List Files: 3 Methods with Examples

  1. You can retrieve a list of all files and folders in a specified directory using the listdir method in the os module. Below is an example of the code.
import os

files = os.listdir('/path/to/directory')

for file in files:
    print(file)
  1. The glob method in the glob module can be used to retrieve a list of files based on a specified wildcard pattern. Here is an example code snippet:
import glob

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

for file in files:
    print(file)
  1. You can use the os.walk method to recursively retrieve a list of all files in a specified directory and its subdirectories. An example code is shown below:
import os

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

These methods can be used to obtain a list of files based on different needs, choose the appropriate method to handle the file list.

bannerAds