24

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']
3
  • 1
    see here: stackoverflow.com/questions/3964681/… Commented Sep 13, 2016 at 14:05
  • 2
    glob.glob('/path/to/dir/*.txt') gives you a list of the required filepaths Commented Sep 13, 2016 at 14:06
  • Read through the documentation and find a package/module that has that functionality then write some code to use it. Commented Sep 13, 2016 at 14:07

1 Answer 1

10

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')
Sign up to request clarification or add additional context in comments.

1 Comment

glob module is the only reasonable answer in the bunch. Don't encourage slow, brittle, and non-portable solutions like calling out to ls, particularly with shell wrapping.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.