Put the code below in code.py on your CIRCUITPY drive, open up the REPL (and restart it with ^D if necessary) to get a listing of all the files an SD card contains. We recursively print out all files and also the filesize. This is a good demo to start with because you can at least tell if your files exist!

This example will work on any board where you've configured mount_sd.py!.

The function print_directory works using os.listdir (to list files in a directory) and os.stat (to get information about an item, such as size or whether it's a directory).

By keeping track of the nesting of directories within directories, names are indented according to the value of tabs to show the directory structure.

# SPDX-FileCopyrightText: 2017 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import os

# pylint: disable=unused-import
import mount_sd # You must create a module mount_sd.py that mounts your sd card!

def print_directory(path, tabs=0):
    for file in os.listdir(path):
        stats = os.stat(path + "/" + file)
        filesize = stats[6]
        isdir = stats[0] & 0x4000

        if filesize < 1000:
            sizestr = str(filesize) + " by"
        elif filesize < 1000000:
            sizestr = "%0.1f KB" % (filesize / 1000)
        else:
            sizestr = "%0.1f MB" % (filesize / 1000000)

        prettyprintname = ""
        for _ in range(tabs):
            prettyprintname += "   "
        prettyprintname += file
        if isdir:
            prettyprintname += "/"
        print('{0:<40} Size: {1:>10}'.format(prettyprintname, sizestr))

        # recursively print directory contents
        if isdir:
            print_directory(path + "/" + file, tabs + 1)


print("Files on filesystem:")
print("====================")
print_directory("/sd")

This guide was first published on Jul 31, 2020. It was last updated on Mar 29, 2024.

This page (Listing files on SD card) was last updated on Mar 29, 2024.

Text editor powered by tinymce.