Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

How do I list all files of a directory?

Solution:

To list all files in a directory in Python, you can use many methods. First, you can use the os module:


import os

directory_path = '/path/to/your/directory'

#Get all files in the directory
files = [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))]

#Print the list of files
print(files)

It’s simple and useful. However, if you have large lists, you must choose other options, such as the pathlib module.


from pathlib import Path 

directory_path = Path('/path/to/your/directory')

#Get all files in the directory 
files = [f for f in directory_path.iterdir() if f.is_file()]

#Print the list of files 
print(files)

Replace '/path/to/your/directory' with the path to the directory you want to list.

Also, you can list files in a Python directory using the walk() method. With this, you can access files deeper in a directory tree.


from os import walk

f = []
layer = 1
w = walk("/Users/yang")
for (dirpath, dirnames, filenames) in w:
     if layer == 2:
          f.extend(dirnames)
          break
     layer += 1

Are you looking for more answers? Follow MarsDevs’ Python blogs.