path – How can I list the contents of a directory in Python?

path – How can I list the contents of a directory in Python?

import os
os.listdir(path) # returns list

One way:

import os
os.listdir(/home/username/www/)

Another way:

glob.glob(/home/username/www/*)

Examples found here.

The glob.glob method above will not list hidden files.

Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir method on Path objects:

from pathlib import Path
print(*Path(/home/username/www/).iterdir(), sep=n)

path – How can I list the contents of a directory in Python?

os.walk can be used if you need recursion:

import os
start_path = . # current directory
for path,dirs,files in os.walk(start_path):
    for filename in files:
        print os.path.join(path,filename)

Leave a Reply

Your email address will not be published. Required fields are marked *