Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all files in a directory with extension .txt in Python

Tags:

python

file-io

How can I find all the files in a directory having the extension .txt in python?

like image 450
usertest Avatar asked Oct 19 '10 01:10

usertest


People also ask

Which command is used to list all the files having extension txt?

locate command syntax: Similarly, you can follow the syntax of locate command for finding all files with any specific extension such as “. txt.”


Video Answer


2 Answers

You can use glob:

import glob, os os.chdir("/mydir") for file in glob.glob("*.txt"):     print(file) 

or simply os.listdir:

import os for file in os.listdir("/mydir"):     if file.endswith(".txt"):         print(os.path.join("/mydir", file)) 

or if you want to traverse directory, use os.walk:

import os for root, dirs, files in os.walk("/mydir"):     for file in files:         if file.endswith(".txt"):              print(os.path.join(root, file)) 
like image 60
ghostdog74 Avatar answered Oct 25 '22 22:10

ghostdog74


Use glob.

>>> import glob >>> glob.glob('./*.txt') ['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt'] 
like image 38
Muhammad Alkarouri Avatar answered Oct 25 '22 20:10

Muhammad Alkarouri