python

How to list all the files in a directory in Python

In this tutorial, we will learn about different ways to get a list of all the files in a directory tree.
 

List all the files in a directory using os.listdir()

listdir() method returns a list containing the names of the entries in the given directory. The list is in an arbitrary order. It does not include special entries ‘.’ And ‘..’ even if they are present in the directory.

import os
 
path = '.'
 
files = os.listdir(path)
for name in files:
    print(name)

Output:

file.txt
image.jpg
doc.pdf
 

List all the files in a directory using os.walk()

The os module contains a list of methods dealing with the file system and the operating system. The walk() method generates the filenames of a directory tree by traversing the tree from top to bottom or bottom to top (the default setting is top to bottom).

os.walk() returns a list of three items. It contains the name of the root directory, a list of subdirectory names, and a list of filenames in the current directory.

import os

for root, directories, files in os.walk("."):  
    for file in files:
        print(file)

Output:

file.txt
image.jpg
doc.pdf

 

List all the files in a directory using glob.glob()

glob.glob() returns the list of files with their full path (unlike os.listdir()) and is more powerful than os.listdir which does not use regular expressions. In addition, glob contains the os, sys and re modules.
 
Example 1: List all .txt files

import glob

files = []
for file in glob.glob("*.txt"):
    files.append(file)

Example 2: List all .txt files by using comprehension list

import glob

files = [file for file in glob.glob("*.txt")]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *