Need to list all text files in a directory using Python?
If so, you may use the following templates to list your files:
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)
In the next section, you’ll see an example with the steps to list all text files using Python.
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:
Old Products
Step 2: Capture the path where the text files are stored
Next, capture the path of the directory where the text files are stored.
For our example, 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 3: List all text files in a directory using Python
To list all the text 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') my_files = glob.glob('*.txt') print(my_files)
And for our example, this is the complete Python code to list the text files:
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']
Don’t forget to place “r” before the 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 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']