[Diaoye learns programming] MicroPython manual built-in module rmdir

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.rmdir(path) is a function used to delete a directory. Its main features, application scenarios, and matters needing attention are as follows:

Main features: os.rmdir(path) accepts a string parameter path, which represents the path of the directory to be deleted. If path does not exist, or path is not an empty directory, or path contains invalid characters, os.rmdir(path) will throw an exception. If path is an empty string, then os.rmdir(path) does nothing.

Application scenario: os.rmdir(path) can be used to delete unnecessary empty directories in the file system. For example, you can use os.rmdir(path) to delete some temporarily created empty directories, some cleared data directories, or some backed up configuration directories.

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

The following are several practical application cases of MicroPython's built-in module os.rmdir(path):

Case 1: Delete an empty directory named 'temp' on the MicroPython board. code show as below:

import os

# 定义要删除的目录路径
path = 'temp'

# 删除目录
os.rmdir(path)

Case 2: Delete a data directory named 'data' on the MicroPython board, provided that the directory has been cleared. code show as below:

import os

# 定义要删除的目录路径
path = 'data'

# 判断目录是否存在
if path in os.listdir():
    # 判断目录是否为空
    if len(os.listdir(path)) == 0:
        # 删除目录
        os.rmdir(path)
        # 打印删除成功信息
        print('Removed', path)
    else:
        # 打印目录非空信息
        print('Directory is not empty:', path)
else:
    # 打印目录不存在信息
    print('No such directory:', path)

Case 3: Delete all empty subdirectories under a certain directory on the MicroPython board. code show as below:

import os

# 定义要删除空子目录的父目录
dir = 'test'

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

# 遍历每个项目
for item in items:
    # 获取项目的完整路径
    full_path = os.path.join(dir, item)
    # 如果项目是一个空目录
    if os.path.isdir(full_path) and len(os.listdir(full_path)) == 0:
        # 删除目录
        os.rmdir(full_path)
        # 打印删除成功信息
        print('Removed', full_path)

Case 4: Delete empty folders:

import os

# 定义要删除的空文件夹路径
folder_path = "/home/pi/empty_folder"

# 检查文件夹是否存在并删除
if os.path.exists(folder_path):
    os.rmdir(folder_path)
    print("已成功删除空文件夹:", folder_path)
else:
    print("文件夹不存在:", folder_path)

In this example, we use the rmdir function of the os module to delete the empty folder under the specified path. First, we check if the folder exists using the os.path.exists function. If the folder exists, we use the os.rmdir function to delete the folder and print out a successful deletion message. If the folder does not exist, print out a message that the folder does not exist.

Case 5: Delete empty folders in batches:

import os

# 定义要删除的空文件夹列表
folders = ["/home/pi/empty_folder1", "/home/pi/empty_folder2", "/home/pi/empty_folder3"]

# 删除空文件夹
for folder in folders:
    if os.path.exists(folder):
        os.rmdir(folder)
        print("已成功删除空文件夹:", folder)
    else:
        print("文件夹不存在:", folder)

In this example, we use the rmdir function of the os module to delete multiple empty folders under the specified path. We define an empty list of folder paths, then use a for loop to iterate through each folder in the list. In each loop, we use the os.path.exists function to check whether the folder exists. If it exists, we use the os.rmdir function to delete the folder and print out a message that the deletion was successful. If the folder does not exist, print out a message that the folder does not exist.

Case 6: Delete non-empty folders:

import shutil

# 定义要删除的非空文件夹路径
folder_path = "/home/pi/non_empty_folder"

# 删除非空文件夹及其内容
shutil.rmtree(folder_path)
print("已成功删除非空文件夹:", folder_path)

In this example, we use the rmtree function of the shutil module to delete non-empty folders and their contents under the specified path. We directly specify the folder path and then use shutil.rmtree function to delete the folder. Finally, we print out the non-empty folder paths that were successfully deleted.

Case 7: Delete empty directories

import uos

# 删除名为 "data" 的空目录
uos.rmdir("data")

This example uses the uos.rmdir() function to delete an empty directory named "data". The rmdir function can only be used to delete empty directories. If the directory contains files or subdirectories, an exception will be thrown.

Case 8: Recursively delete a directory and its contents

import uos

# 递归删除目录及其内容
uos.rmtree("project")

In this example, we use the uos.rmtree() function to recursively delete the directory named "project" and its contents. The rmtree function can delete non-empty directories, and will recursively delete all files and subdirectories under the directory.

Case 9: Deleting specific types of directories in batches

import uos

# 删除根目录下所有以 "backup_" 开头的目录
dirs = uos.listdir()
for dir in dirs:
    if dir.startswith("backup_"):
        uos.rmdir(dir)

In this example, we use the uos.listdir() function to list all files and subdirectories under the root directory, and use a loop to iterate through each directory. We filter out certain types of directories by checking if their names start with "backup_" and delete them using the uos.rmdir() function.

These examples show the uos.rmdir() function in action, including removing empty directories, recursively removing directories and their contents, and batch removing certain types of directories. By using the rmdir function, you can easily delete directories on MicroPython devices. Please note that when using the rmdir function, please ensure sufficient permissions and reasonable path settings, and make appropriate adjustments and processing according to actual needs.

Insert image description here

おすすめ

転載: blog.csdn.net/weixin_41659040/article/details/132787268