Alex Rivera | Logout

How do I list all files of a directory?

Asked 2010-07-08T19:31:22.803
3464

How can I list all files of a directory in Python and add them to a list?

Edit
Report

2 Answers

2654

I prefer using the glob module, as it does pattern matching and expansion.

import glob
print(glob.glob("/home/adam/*"))

It does pattern matching intuitively

import glob
# All files and directories ending with .txt and that don't begin with a dot:
print(glob.glob("/home/adam/*.txt")) 
# All files and directories ending with .txt with depth of 2 folders, ignoring names beginning with a dot:
print(glob.glob("/home/adam/*/*.txt")) 

It will return a list with the queried files and directories:

['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]

Note that glob ignores files and directories that begin with a dot ., as those are considered hidden files and directories, unless the pattern is something like .*.

Use glob.escape to escape strings that are not meant to be patterns:

print(glob.glob(glob.escape(directory_name) + "/*.txt"))
answered 2010-07-09T18:13:37.043
3

dircache is "Deprecated since version 2.6: The dircache module has been removed in Python 3.0."

import dircache
list = dircache.listdir(pathname)
i = 0
check = len(list[0])
temp = []
count = len(list)
while count != 0:
  if len(list[i]) != check:
     temp.append(list[i-1])
     check = len(list[i])
  else:
    i = i + 1
    count = count - 1

print temp
answered 2012-07-25T10:25:54.027

Your Answer