【Diao Ye learns programming】MicroPython manual built-in module remove

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

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

Application scenario: os.remove(path) can be used to delete unnecessary files in the file system. For example, you can use os.remove(path) to delete some temporary files, some incorrectly downloaded files, or some files that have been backed up.

Things to note: Before using os.remove(path), you need to ensure that path is a legal path and path is an existing file. Otherwise, os.remove(path) will fail and throw an exception. Additionally, if path is a relative path, it is relative to the current working directory. Therefore, before using os.remove(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 some practical application cases of MicroPython's built-in module os.remove(path):

Case 1: Delete a file named 'test.txt' on the MicroPython board. code show as below:

import os

# 定义要删除的文件路径
path = 'test.txt'

# 删除文件
os.remove(path)

Case 2: Delete an old script file named 'old.py' on the MicroPython board. code show as below:

import os

# 定义要删除的文件路径
path = 'old.py'

# 判断文件是否存在
if path in os.listdir():
    # 删除文件
    os.remove(path)
    # 打印删除成功信息
    print('Removed', path)
else:
    # 打印文件不存在信息
    print('No such file:', path)

Case 3: Delete all script files with the .py suffix in a certain directory on the MicroPython board. code show as below:

import os

# 定义要删除文件的目录
dir = 'scripts'

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

# 遍历每个项目
for item in items:
    # 获取项目的完整路径
    full_path = os.path.join(dir, item)
    # 如果项目是一个.py后缀的脚本文件
    if full_path.endswith('.py'):
        # 删除文件
        os.remove(full_path)
        # 打印删除成功信息
        print('Removed', full_path)

Case 4: Delete a single file:

import os

# 定义要删除的文件路径
file_path = "/home/pi/documents/file.txt"

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

In this example, we use the remove function of the os module to delete the files in the specified path. First, we check if the file exists using the os.path.exists function. If the file exists, we use the os.remove function to delete the file and print out a successful deletion message. If the file does not exist, a message that the file does not exist is printed.

Case 5: Batch delete files in a folder:

import os

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

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

# 删除文件夹中的所有文件
for file in files:
    file_path = os.path.join(folder, file)
    os.remove(file_path)
    print("已成功删除文件:", file_path)

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 remove each file using the os.remove function. Finally, we print out the successfully deleted file paths.

Case 6: Delete empty folders:

import os

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

# 删除空文件夹
os.rmdir(folder)
print("已成功删除空文件夹:", folder)

In this example, we use the rmdir function of the os module to delete the empty specified folder. We directly specify the folder path and then use the os.rmdir function to delete the folder. Finally, we print out the empty folder path that was successfully deleted. These examples show three practical application cases using MicroPython's built-in module remove. By using the remove function, you can delete individual files, batch delete files in folders, and delete empty folders.

Case 7: Deleting specific types of files in batches

import uos

# 删除当前目录中所有的日志文件
files = uos.listdir()
for file in files:
    if file.endswith('.log'):
        uos.remove(file)

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 file. We filter out the log files by checking if their names end with ".log" and delete them using the uos.remove() function.

Case 8: Delete a directory and its contents

import uos

# 删除名为 "data" 的目录及其内容
uos.rmdir("data")

In this example, we use the uos.rmdir() function to delete a directory named "data" and its contents. Note that the rmdir function can only be used to delete empty directories. If the directory contains files or subdirectories, an exception will be thrown.

These cases demonstrate the practical application of the uos.remove() function, including deleting a single file, deleting files of a specific type in batches, and deleting a directory and its contents. By using the remove function, you can easily delete files on the MicroPython device. Please note that when using the remove function, please ensure that you have sufficient permissions and reasonable path settings, and make appropriate adjustments and processing according to actual needs.

Insert image description here

Guess you like

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