Ask coding questions

← Back to all posts
Directory for python repl?
MichelleSanche2 (2)

I have a program where I want to look through a folder for data. How would I list that directory if I upload the folder to my repl?

Scoder12 (881)

os.listdir() will show everything in the directory including files and directories. Docs here

If you want files only, you could either filter this down using os.path Docs here:

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

or you could use os.walk() (Docs here) which gives a list of directories and files separately. If you only want the top directory you can just break the first time it yields

from os import walk

found_files = []
for (dirpath, dirnames, filenames) in walk(mypath):

If you want to put the files in a list you can use .extend() Docs Here

If this helped, please hit the check button and leave an upvote.

abc3354 (229)

@Scoder12 Good and complete answer ! Thanks ;)
@MichelleSanche2 If this post answered your question please mark it as the answer