Open All the Files in a Directory in Python

In this tutorial, we will go through how to open all the files in a directory using the Python os.listdir() and glob.glob() functions.

 

Open All the Files in a Directory Using the os.listdir() Function in Python

The Python os package contains the listdir() function which returns a list of all the filenames inside a directory. We can use a for loop to iterate over each filename and open them with the open() function.

 

import os

path = '/path/to/dir'

for filename in os.listdir(path):
  with open(os.path.join(path, filename), 'r') as f:
      data = f.read()
      print(data)
First line of file.
Second line of file.

 

Open All the Files in a Directory Using the os.listdir() Function in Python

The glob() function from the glob package returns files in a directory that match a given regex pattern.

 

To open all files in the current working directory, we would use the pattern ./*, iterate of them and open each file with the open() function.

 

import glob
import os

for filename in glob.glob('./*'):
   with open(os.path.join('.', filename), 'r') as f:
       data = f.read()
       print(data)
First line of file.
Second line of file.