Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python : get list all *.txt files in a directory [duplicate]

Tags:

i'm beginner in python language

how to get list all .txt file in a directory in python language ?

for example get list file :

['1.txt','2.txt','3.txt','4.txt','5.txt','6.txt']
like image 493
changle Avatar asked Sep 13 '16 14:09

changle


People also ask

How do you list all files in a directory with a certain extension in Python?

The method os. listdir() lists all the files present in a directory. We can make use of os. walk() if we want to work with sub-directories as well.


1 Answers

you can use os, subprocess and glob library

os library example:

import os
os.system("ls *.txt")

this command returned all .txt file

subprocess library example:

my_result_command = subprocess.Popen(['ls', '-l'], stdout=log, stderr=log, shell=True)

you can check my_result_command and get all file or .txt file

glob library example:

import glob
glob.glob('*.txt')
like image 133
Mikail Land Avatar answered Sep 24 '22 13:09

Mikail Land