Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

file
directory
python
list

How to list files in a directory in Python

Educative Answers Team

In Python, we may want a list of files or folders in a specified directory. There are several methods that can be used to do this.

svg viewer

1. Using the os module

Python’s os module provides a function that gets a list of files or folders in a directory. The ., which is passed as an argument to os.listdir(), signifies the current folder.

main.py
file3.py
file2.csv
file1.txt
import os
arr = os.listdir('.')
print(arr)

To list files at a specific path, we can simply give the path as a string to the function.

This path will have to be relative to where your Python file is placed or, if you’re not working with files, the path will be relative to where your Python Shell has been launched:

os.listdir('My_Downloads/Music')

2. Using the glob module

The glob module also makes it possible​ to get a list of files or folders in a directory.

main.py
file3.py
file2.csv
file1.txt
import glob
print(glob.glob('.'))

We can also print the filenames recursively using the iglob method. In the method call, the recursive parameter must be set to True.

for file_name in glob.iglob('Desktop/**/*.txt', recursive=True):
  print(file_name)

The code above will search the Desktop folder recursively and print all .txt files. We can replace *.txt with only a * to print all files.

The ** command is used to search recursively and is only applicable when the recursive parameter is True.

RELATED TAGS

file
directory
python
list
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring