Python Traverse Files in a Directory for Beginners – Python Tutorial

By | December 17, 2019

Traversing a directory means get all files or subdirectories in it. To do it, we should know:

How to check a file is file

How to check a file is directory

In this tutorial, we will write an example to show you how to traverse a directory in python.

Python Traverse Files in a Directory for Beginners

Import os library

import os

Define a list to store all files path

files = []

Define a function to traverse a directory

def traverseDir(dir):
    files = []
    for entry in os.scandir(dir):
        if entry.is_dir():
            files_temp = traverseDir(entry.path)
            if files_temp:
                files.extend(files_temp)
        elif entry.is_file():
            files.append(entry.path)
    return files

In this function, we should know:

entry.is_dir() and entry.is_file() is the key.

Print result

The result is:

['F:\\PDF-Documents\\Tutorials\\Insert Image Watermark into Word.docx', 'F:\\PDF-Documents\\Tutorials\\introduction-to-tensorflow.pdf', 'F:\\PDF-Documents\\Tutorials\\introduction-to-tensorflow.txt', 'F:\\PDF-Documents\\Tutorials\\Transferring Files Using HTTP or HTTPS.pdf', 'F:\\PDF-Documents\\Tutorials\\~$sert Image Watermark into Word.docx']

Notice: Using os.scandir() function, we can get hidden files and directories.

Meanwhile, we also may encounter:PermissionError if you are traversing some directories, such as F:\\$RECYCLE.BIN\\S-1-5-18.

We can edit traverseDir() using try except statement like below:

def traverseDir(dir):
    files = []
    try:
        for entry in os.scandir(dir):
            if entry.is_dir():
                files_temp = traverseDir(entry.path)
                if files_temp:
                    files.extend(files_temp)
            elif entry.is_file():
                files.append(entry.path)
    except:
        pass
    return files

Leave a Reply