How can I find all the files in a directory having the extension .txt
in python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Many users have replied with
os.walk
answers, which includes all files but also all directories and subdirectories and their files.Or for a one off where you don't need a generator:
If you are going to use matches for something else, you may want to make it a list rather than a generator expression:
For me. It's classic.
use Python OS module to find files with specific extension.
the simple example is here :
Try this this will find all your file inside folder or folder
You can try this code:
I did a test (Python 3.6.4, W7x64) to see which solution is the fastest for one folder, no subdirectories, to get a list of complete file paths for files with a specific extension.
To make it short, for this task
os.listdir()
is the fastest and is 1.7x as fast as the next best:os.walk()
(with a break!), 2.7x as fast aspathlib
, 3.2x faster thanos.scandir()
and 3.3x faster thanglob
.Please keep in mind, that those results will change when you need recursive results. If you copy/paste one method below, please add a .lower() otherwise .EXT would not be found when searching for .ext.
Results: