List all Text Files in a Directory using Python

To list all text files in a directory using Python:

List all the text files in a directory:

import glob
import os

os.chdir(r"directory where the files are located")

my_files = glob.glob("*.txt")

print(my_files)

List the paths of the text files:

import glob

my_files_path = glob.glob(r"directory where the files are located\*.txt")

print(my_files_path)

Steps to List all Text Files in a Directory using Python

Step 1: Locate the directory that contains the text files

For example, let’s suppose that the following 2 text files are stored in a folder called Test:

New Products
Old Products

Assume that the path where the 2 files are stored is as follows:

C:\Users\Ron\Desktop\Test

You’ll need to modify the path to reflect the location where the text files are stored on your computer.

Step 2: List all text files in a directory using Python

Use the following template to list your text files:

import glob
import os

os.chdir(r"directory where the files are located")

my_files = glob.glob("*.txt")

print(my_files)

For our example:

import glob
import os

os.chdir(r"C:\Users\Ron\Desktop\Test")

my_files = glob.glob("*.txt")

print(my_files)

Run the code (adjusted to your path) and you’ll see the list of the text files:

['New Products.txt', 'Old Products.txt']

Optional Step: List the paths of the text files

What if you want to list the paths of your text files?

If that’s the case, you may use the following template:

import glob

my_files_path = glob.glob(r"directory where the files are located\*.txt")

print(my_files_path)

And for our example:

import glob

my_files_path = glob.glob(r"C:\Users\Ron\Desktop\Test\*.txt")

print(my_files_path)

These are the paths for our example:

['C:\\Users\\Ron\\Desktop\\Test\\New Products.txt', 
'C:\\Users\\Ron\\Desktop\\Test\\Old Products.txt']

Leave a Comment