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

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

Main features: os.rename(old_path, new_path) accepts two string parameters old_path and new_path, which represent the original path and new path of the file to be renamed. If old_path does not exist, or old_path is not a file, or old_path or new_path contains invalid characters, then os.rename(old_path, new_path) will throw an exception. If old_path and new_path are the same, then os.rename(old_path, new_path) will not do anything.

Application scenario: os.rename(old_path, new_path) can be used to modify the name or location of a file in the file system. For example, you can use os.rename(old_path, new_path) to move a file from one directory to another, or change the extension of a file to another extension.

Things to note: Before using os.rename(old_path, new_path), you need to ensure that old_path is a legal path and old_path is an existing file. Otherwise, os.rename(old_path, new_path) will fail and throw an exception. Additionally, if old_path or new_path is a relative path, they are relative to the current working directory. Therefore, before using os.rename(old_path, new_path), it is best to use os.getcwd() to get the current working directory and adjust the value of old_path or new_path as needed.

The following are several practical application examples of MicroPython's built-in module os.rename(old_path, new_path):

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

import os

# 定义要重命名的文件的原路径和新路径
old_path = 'test.txt'
new_path = 'result.txt'

# 重命名文件
os.rename(old_path, new_path)

Case 2: Move a script file named 'hello.py' from the root directory to the 'scripts' directory on the MicroPython board, and rename it to 'greet.py'. code show as below:

import os

# 定义要重命名的文件的原路径和新路径
old_path = '/hello.py'
new_path = '/scripts/greet.py'

# 重命名文件
os.rename(old_path, new_path)

Case 3: Change the extension of an image file named 'image.jpg' to '.png' on the MicroPython board. code show as below:

import os

# 定义要重命名的文件的原路径和新路径
old_path = 'image.jpg'
new_path = 'image.png'

# 重命名文件
os.rename(old_path, new_path)

Case 4: Rename the file:

import os

# 定义原始文件路径和新文件路径
old_file_path = "/home/pi/documents/old_file.txt"
new_file_path = "/home/pi/documents/new_file.txt"

# 检查原始文件是否存在并重命名
if os.path.exists(old_file_path):
    os.rename(old_file_path, new_file_path)
    print("已成功将文件重命名为:", new_file_path)
else:
    print("原始文件不存在:", old_file_path)

In this example, we use the rename function of the os module to rename the file under the specified path. We define the original file path and the new file path, and then use the os.path.exists function to check if the original file exists. If the file exists, we use the os.rename function to rename the file to the new file path and print out a successful rename message. If the original file does not exist, a message that the original file does not exist is printed.

Case 5: Batch rename files in a folder:

import os

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

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

# 批量重命名文件夹中的文件
for file in files:
    old_name = os.path.join(folder, file)
    new_name = os.path.join(folder, "new_" + file)
    os.rename(old_name, new_name)
    print("已成功将文件重命名为:", new_name)

In this example, we use the rename function of the os module to batch rename the files in the folder. We use the os.listdir function to get the file list in the specified folder, and then use a for loop to traverse the file list. In each loop, we use the os.path.join function to define the original file path and the new file path, and then use the os.rename function to rename the file to the new file path and print out a message that the rename was successful.

Case 6: Move the file and rename it:

import os

# 定义要移动的文件路径和目标文件夹路径
file_path = "/home/pi/documents/file.txt"
target_folder = "/home/pi/archive"

# 检查文件是否存在并移动重命名
if os.path.exists(file_path):
    new_file_path = os.path.join(target_folder, "new_file.txt")
    os.rename(file_path, new_file_path)
    print("已成功将文件移动并重命名为:", new_file_path)
else:
    print("文件不存在:", file_path)

In this example, we use the rename function of the os module to move the file to the specified target folder and rename it. We define the original file path, the destination folder path, and the new file path. First, we check if the file exists using the os.path.exists function. If the file exists, we use the os.path.join function to define a new file path, and use the os.rename function to move the file to the target folder and rename it to the new file path, and print out a message that the move and rename was successful. If the file does not exist, a message that the file does not exist is printed.

Case 7: Renaming files

import uos

# 将文件名为 "old.txt" 的文件重命名为 "new.txt"
uos.rename("old.txt", "new.txt")

This example uses the uos.rename() function to rename a file named "old.txt" to "new.txt".

Case Eight: Moving Files

import uos

# 将文件从 "dir1" 目录移动到 "dir2" 目录
uos.rename("dir1/file.txt", "dir2/file.txt")

In this example, we use the uos.rename() function to move a file named "file.txt" from the "dir1" directory to the "dir2" directory. You can specify a new destination when moving files by providing the full path.

Case 9: Rename files in batches

import uos

# 批量重命名文件名以 "image" 开头的文件
files = uos.listdir()
for file in files:
    if file.startswith("image"):
        new_name = "new_" + file
        uos.rename(file, new_name)

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 specific types of files by checking if their names start with "image" and rename them to new file names using the uos.rename() function.

These cases demonstrate the practical application of the uos.rename() function, including renaming files, moving files, and batch renaming files. By using the rename function, you can easily rename and move files on MicroPython devices. Please note that when using the rename 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/132787277