How can I list the contents of a directory in Python?
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 How Can I List The Contents Of A Directory In Python?
00:11 Answer 1 Score 19
00:18 Accepted Answer Score 349
00:25 Answer 3 Score 15
00:50 Answer 4 Score 80
01:18 Thank you
--
Full question
https://stackoverflow.com/questions/2759...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #path
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 How Can I List The Contents Of A Directory In Python?
00:11 Answer 1 Score 19
00:18 Accepted Answer Score 349
00:25 Answer 3 Score 15
00:50 Answer 4 Score 80
01:18 Thank you
--
Full question
https://stackoverflow.com/questions/2759...
--
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/")
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")
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.