How to List all txt Files in a Directory using Python

Need to list all txt files in a directory using Python?

If so, you may use the following templates to list your files:

List all the txt files in a directory:

import glob
import os

os.chdir(r'directory where the files are located')
myFiles = glob.glob('*.txt')
print(myFiles)

List the paths of the txt files:

import glob

myFilesPaths = glob.glob(r'directory where the files are located\*.txt')
print(myFilesPaths)

In the next section, I’ll review an example with the steps to list all text files using Python.

Steps to List all txt Files in a Directory using Python

Step 1: Locate the directory that contains the txt files

For example, I stored two text files (“Client Names” and “Shipping Address”) inside a folder called Test:

How to List all txt Files in a Directory using Python

Step 2: Capture the path where the txt files are stored

Next, capture the path where the text files are stored. In my case, the path where I stored the two text files is:

C:\Users\Ron\Desktop\Test

path of a folder

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

Step 3: List all txt files in a directory using Python

To list all the txt files in a directory using Python, you’ll need to import the glob and os packages.

You can then use the following template to list your text files:

import glob
import os

os.chdir(r'directory where the files are located')
myFiles = glob.glob('*.txt')
print(myFiles)

And for our example, this is the complete Python code that I used to list the text files:

import glob
import os

os.chdir(r'C:\Users\Ron\Desktop\Test')
myFiles = glob.glob('*.txt')
print(myFiles)

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

List all txt Files in a Directory using Python

Don’t forget to put “r” before the file path to avoid the following error in Python:

(unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

Optional Step: List the paths of the text files

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

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

import glob

myFilesPaths = glob.glob(r'directory where the files are located\*.txt')
print(myFilesPaths)

And for our example:

import glob

myFilesPaths = glob.glob(r'C:\Users\Ron\Desktop\Test\*.txt')
print(myFilesPaths)

These are the paths that I got when running the code:

paths of text files