Python: get a list of all * .txt files in a directory

I'm new to python

How to get a list of all files .txtin a python directory?

for example, get a list file:

['1.txt','2.txt','3.txt','4.txt','5.txt','6.txt']
+4
source share
1 answer

you can use libraries os, subprocessandglob

os Library example:

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

this command returned the whole .txtfile

subprocess Library example:

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

you can check my_result_command and get the whole file or .txtfile

glob Library example:

import glob
glob.glob('*.txt')
+3
source

Source: https://habr.com/ru/post/1654471/


All Articles