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

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

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

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
print(glob.glob('./*.txt'))

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')]
print(text_files)

  • 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/'

print(list(pathlib.Path(path).glob('*.txt')))

  • 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

LEAVE A REPLY

Please enter your comment!
Please enter your name here