[Diao Ye learns programming] MicroPython manual built-in module listdir

Insert image description here

MicroPython is a lightweight version of the interpreter designed to run the Python 3 programming language in embedded systems. Compared with regular Python, the MicroPython interpreter is small (only about 100KB) and is compiled into a binary Executable file to run, resulting in higher execution efficiency. It uses a lightweight garbage collection mechanism and removes most of the Python standard library to accommodate resource-constrained microcontrollers.

The main features of MicroPython include:
1. The syntax and functions are compatible with standard Python, making it easy to learn and use. Supports most of Python's core syntax.
2. Directly access and control the hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. A powerful module system that provides functions such as file system, network, and graphical interface.
4. Support cross-compilation to generate efficient native code, which is 10-100 times faster than the interpreter.
5. The amount of code is small, and the memory usage is small, which is suitable for running on MCU and development boards with small memory.
6. Open source license, free to use. The Shell interactive environment provides convenience for development and testing.
7. The built-in I/O driver supports a large number of microcontroller platforms, such as ESP8266, ESP32, STM32, micro:bit, control board and PyBoard, etc. There is an active community.

The application scenarios of MicroPython include:
1. Quickly build prototypes and user interactions for embedded products.
2. Make some small programmable hardware projects.
3. As an educational tool, it helps beginners learn Python and IoT programming.
4. Build smart device firmware to achieve advanced control and cloud connectivity.
5. Various microcontroller applications such as Internet of Things, embedded intelligence, robots, etc.

Pay attention to the following when using MicroPython:
1. The memory and Flash space are limited.
2. The explanation and execution efficiency is not as good as C language.
3. Some library functions are different from the standard version.
4. Optimize the syntax for the platform and correct the differences with standard Python.
5. Use memory resources rationally and avoid frequently allocating large memory blocks.
6. Use native code to improve the performance of speed-critical parts.
7. Use abstraction appropriately to encapsulate underlying hardware operations.

Generally speaking, MicroPython brings Python into the field of microcontrollers, which is an important innovation that not only lowers the programming threshold but also provides good hardware control capabilities. It is very suitable for the development of various types of Internet of Things and intelligent hardware.

Insert image description here

MicroPython's built-in module os provides some basic operating system services, including file system access and management. Among them, os.listdir(dir) is a function used to list files and folders in a directory. Its main features, application scenarios, and matters needing attention are as follows:

main feature:

os.listdir(dir) accepts a string argument dir representing the path of the directory to list. If dir is not specified, the current directory is listed by default. os.listdir(dir) returns a list containing the names of all files and folders in dir. os.listdir(dir) throws an exception if dir does not exist, or if dir is not a directory.

Application scenarios:

os.listdir(dir) can be used to view and traverse the contents of directories in the file system. For example, you can use os.listdir(dir) to check which files and folders are in a certain directory, and then operate as needed. You can also use os.listdir(dir) to traverse all files and folders in a directory, and then process each item.

Things to note:

Before using os.listdir(dir), you need to ensure that dir is a legal path, and dir is an existing directory. Otherwise, os.listdir(dir) fails with an exception. Also, if dir is a relative path, it is relative to the current working directory. Therefore, before using os.listdir(dir), it is best to use os.getcwd() to obtain the current working directory, and adjust the value of dir as needed.

The following are several practical application examples of MicroPython's built-in module os.listdir(dir):

Case 1: Check what drives are in the root directory (such as /flash, /sd, etc.) on the MicroPython board. code show as below:

import os

# 列出根目录下的所有驱动器
drives = os.listdir('/')

# 打印驱动器列表
print(drives)

Case 2: Delete all empty files (size 0 bytes) in a certain directory on the MicroPython board. code show as below:

import os

# 定义要删除空文件的目录
path = 'test'

# 列出该目录下的所有文件和文件夹
items = os.listdir(path)

# 遍历每个项目
for item in items:
    # 获取项目的完整路径
    full_path = os.path.join(path, item)
    # 如果项目是一个文件
    if os.path.isfile(full_path):
        # 获取文件的大小
        size = os.stat(full_path)[6]
        # 如果文件大小为0
        if size == 0:
            # 删除文件
            os.remove(full_path)
            # 打印删除信息
            print('Removed', full_path)

Case 3: Count the number and total size of all image files (ending with .jpg or .png) in a certain directory on the MicroPython board. code show as below:

import os

# 定义要统计图像文件的目录
path = 'images'

# 列出该目录下的所有文件和文件夹
items = os.listdir(path)

# 初始化图像文件数量和总大小为0
count = 0
total_size = 0

# 遍历每个项目
for item in items:
    # 获取项目的完整路径
    full_path = os.path.join(path, item)
    # 如果项目是一个图像文件(以.jpg或.png结尾)
    if full_path.endswith('.jpg') or full_path.endswith('.png'):
        # 增加图像文件数量
        count += 1
        # 获取文件大小,并累加到总大小中
        size = os.stat(full_path)[6]
        total_size += size

# 打印图像文件数量和总大小
print('There are', count, 'image files in', path)
print('The total size is', total_size, 'bytes')

Case 4: Display all files in the folder:

import os

# 定义目标文件夹
folder = "/home/pi/projects"

# 获取文件列表
files = os.listdir(folder)

# 打印所有文件
print("文件列表:")
for file in files:
    print(file)

In this example, we use the listdir function of the os module to get the list of files in the specified folder. We then iterate through the list of files and print each file.

Case 5: Count the number of files in a folder:

import os

# 定义目标文件夹
folder = "/home/pi/documents"

# 获取文件列表
files = os.listdir(folder)

# 统计文件数量
file_count = len(files)

# 打印文件数量
print("文件夹中的文件数量:", file_count)

In this example, we use the listdir function of the os module to get the list of files in the specified folder. Then, we use the len function to calculate the length of the file list, which is the number of files. Finally, print out the number of files in the folder.

Case 6: Delete specified files in the folder:

import os

# 定义目标文件夹
folder = "/home/pi/photos"

# 获取文件列表
files = os.listdir(folder)

# 定义要删除的文件名
file_to_delete = "image.jpg"

# 检查文件是否存在并删除
if file_to_delete in files:
    file_path = os.path.join(folder, file_to_delete)
    os.remove(file_path)
    print("已删除文件:", file_to_delete)
else:
    print("文件不存在:", file_to_delete)

In this example, we use the listdir function of the os module to get the list of files in the specified folder. We then check to see if the file to be deleted exists in the file list. If it exists, we delete the file using the remove function of the os module and print out the deleted file name. If the file does not exist, a message that the file does not exist is printed.

Case 7: List files and subdirectories in a directory

import uos

# 列出当前目录中的所有文件和子目录
items = uos.listdir()

# 遍历目录中的条目
for item in items:
    print(item)

This example uses the uos.listdir() function to list all files and subdirectories in the current directory and stores the result in the items variable. We then iterate through the items using a loop and print the name of each item.

Case 8: Filter specific types of files

import uos

# 列出当前目录中的所有 Python 脚本文件
items = uos.listdir()
for item in items:
    if item.endswith('.py'):
        print(item)

In this example, we use the uos.listdir() function to list all files and subdirectories in the current directory and use a loop to iterate over each entry. We filter out Python script files by checking whether each entry's name ends with ".py" and print them out.

Case 9: Scan specific files in a directory

import uos

# 列出当前目录中所有的图片文件
items = uos.listdir()
for item in items:
    if item.endswith(('.jpg', '.png', '.gif')):
        print(item)

In this example, we use the uos.listdir() function to list all files and subdirectories in the current directory and use a loop to iterate over each entry. We filter out image files by checking whether each entry's name ends with ".jpg", ".png", or ".gif" and print them out.

These cases demonstrate the uos.listdir() function in action, including listing files and subdirectories in a directory, filtering files of specific types, and scanning a directory for specific files. By using the listdir function, you can flexibly handle files and directories on a MicroPython device and perform further operations and processing as needed.

have to be aware of is:

When using the listdir function, make sure that the specified directory path is correct and has appropriate permissions.
MicroPython's file system may have some limitations, such as filename length limitations, path depth limitations, etc. Please ensure that your application functions properly within these constraints.
For large directories or nested directories, the result returned by the listdir function may consume more memory. When working with large directories, consider using an iterator to get entries one by one to reduce memory usage.
When working with files and directories, always remember to implement error and exception handling to ensure the robustness and stability of your code.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/132787257