How can I list the contents of a directory in Python?
PythonPathPython Problem Overview
Can’t be hard, but I’m having a mental block.
Python Solutions
Solution 1 - Python
import os
os.listdir("path") # returns list
Solution 2 - Python
One way:
import os
os.listdir("/home/username/www/")
glob.glob("/home/username/www/*")
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")
Solution 3 - 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)
Solution 4 - Python
glob.glob
or os.listdir
will do it.
Solution 5 - Python
The os
module handles all that stuff.
> os.listdir(path)
>
> Return a list containing the names of the entries in the directory given by path.
> The list is in arbitrary order. It does not include the special entries '.' and
> '..' even if they are present in the directory.
>
> Availability: Unix, Windows.
Solution 6 - Python
In Python 3.4+, you can use the new pathlib
package:
from pathlib import Path
for path in Path('.').iterdir():
print(path)
Path.iterdir()
returns an iterator, which can be easily turned into a list
:
contents = list(Path('.').iterdir())
Solution 7 - Python
Since Python 3.5, you can use os.scandir
.
The difference is that it returns file entries not names. On some OSes like windows, it means that you don't have to os.path.isdir/file
to know if it's a file or not, and that saves CPU time because stat
is already done when scanning dir in Windows:
example to list a directory and print files bigger than max_value
bytes:
for dentry in os.scandir("/path/to/dir"):
if dentry.stat().st_size > max_value:
print("{} is biiiig".format(dentry.name))
(read an extensive performance-based answer of mine here)
Solution 8 - Python
Below code will list directories and the files within the dir. The other one is os.walk
def print_directory_contents(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)