The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC E Schuberts Piano Sonata D 784 in A

--

Chapters
00:00 Question
00:18 Accepted answer (Score 342)
00:28 Answer 2 (Score 74)
01:12 Answer 3 (Score 48)
01:28 Answer 4 (Score 18)
01:41 Thank you

--

Full question
https://stackoverflow.com/questions/2759...

Answer 1 links:
[Another way]: http://docs.python.org/library/glob.html...
[Examples found here]: http://diveintopython.net/file_handling/...
[pathlib]: https://docs.python.org/3/library/pathli...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #path

#avk47



ACCEPTED ANSWER

Score 349


import os
os.listdir("path") # returns list



ANSWER 2

Score 80


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



ANSWER 3

Score 19


glob.glob or os.listdir will do it.




ANSWER 4

Score 15


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.