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


Question

Can’t be hard, but I’m having a mental block.

1
154
5/3/2010 4:01:25 PM

Accepted Answer

import os
os.listdir("path") # returns list
222
5/3/2010 3:57:30 PM

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")

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon