views:

19988

answers:

5

How do I get a list of all files (and directories) in a given directory in Python?

+24  A: 

You can use os.listdir(path). See more os functions here: http://docs.python.org/lib/os-file-dir.html

rslite
+9  A: 
import os



for filename in os.listdir("C:\\temp"):
    print  filename
curtisk
Pass it a Unicode string to get Unicode return value.
Craig McQueen
+1  A: 

Try this:

import os
for top, dirs, files in os.walk('./'):
    for nm in files:       
        print os.path.join(top, nm)
paxdiablo
+26  A: 

This is a way to traverse every file and directory in a directory tree:

import os

for dirname, dirnames, filenames in os.walk('.'):
    for subdirname in dirnames:
        print os.path.join(dirname, subdirname)
    for filename in filenames:
        print os.path.join(dirname, filename)
Jerub
+2  A: 

Here's a helper function I use quite often:

import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]
giltay
What does this do?
GavinR