How to Find all Files in a Directory with Extension .txt in Python

Share This Post

Is finding all files in a directory with extension .txt in Python stuck? learn how to find

To fix this you need to use a library called “os” and the second is “glob” let’s get started.

Find all Files in a Directory with Extension .txt in Python?

First of all, to understand this error, such a library may help you out in good ways.

import glob

In the output, it will return such results like:

Find all Files in a Directory with Extension .txt in Python

It is pretty easy to use and understand.

And in an alternative, you have more options to find out all .txt files by the following code.

import os
path = 'E:/Local Disk E/jquery_testing/'
text_files = [f for f in os.listdir(path) if f.endswith('.txt')]

  • First of all, you have to use “import” word in starting line to explain what you wanna import from the provided libraries.
  • And in the second line there you are to let the folder exact path where the all .txt file exists already.
  • And then you are to run for loop in one line. And an alternative is to break while the loop may not work perfectly.
  • Okay, then just simply use the print function to see the result.

Output result:


Find all Files in a Directory with Extension .txt in Python

That’s it.

Alternative ways to find out all .txt files from a directory using Python

It is simple to use another library that works perfectly as an import os library works.

In this way, you will require to have “pathlib” that brings all .txt files from your chosen directory in Python.

import pathlib
path = 'E:/Local Disk E/jquery_testing/'


  • So guys, first you are to put which or what the exact library you want.
  • Then required a path of exact folder or directly.
  • And then in the last not least just simplify put the print function and get the result according you want.
  • In this function, you have to let the programming that path is library then there has an official function, and then call out the path, in the end, what you wanna know?

find out all .txt file from a directory using Python

This way, provide an exact path of all .txt files either letting you can pick up which .txt file you want and then editing by Python.

Read More: How to read a text file into a string variable and strip newlines


Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img