1. Overview of the File System
The MicroPython on ESP32 uses the FAT file system by default, stored in internal flash memory or on an external SD card. The main operations include file reading and writing, directory management, and retrieving file information.
2. Common APIs
<span>os.listdir()</span>: List directory contents<span>os.mkdir(path)</span>: Create a directory<span>os.rmdir(path)</span>: Remove a directory<span>os.remove(path)</span>: Delete a file<span>os.rename(old, new)</span>: Rename a file/directory<span>os.stat(path)</span>: Get file information<span>open()</span>: Open a file (modes:<span>r</span>for read,<span>w</span>for write,<span>a</span>for append,<span>b</span>for binary)
Command 1:

Command 2:
Command Test:

3. Test Code
Basic operations of the file system:
import os
def test_filesystem():
# List root directory contents
print("Root directory contents:")
for item in os.listdir():
print(f"- {item}")
# Create test directory
test_dir = "test_dir"
try:
os.mkdir(test_dir)
print(f"\nCreated directory: {test_dir}")
except OSError:
print(f"\nDirectory already exists: {test_dir}")
# Change to test directory
os.chdir(test_dir)
print(f"Current directory: {os.getcwd()}")
# Write to file
with open("test.txt", "w") as f:
f.write("Hello, ESP32!\n")
f.write("This is a test file.\n")
f.close()
print("Wrote to file: test.txt")
# Read file
with open("test.txt", "r") as f:
content = f.read()
f.close()
print("\nFile content:")
print(content)
# Append content
with open("test.txt", "a") as f:
f.write("Appended line.\n")
f.close()
print("Appended content to file")
# Read file again
with open("test.txt", "r") as f:
print("\nUpdated content:")
print(f.read())
f.close()
# Get file information
stats = os.stat("test.txt")
print(f"\nFile size: {stats[6]} bytes")
# Rename file
os.rename("test.txt", "new_test.txt")
print("File renamed to: new_test.txt")
# List current directory
print("\nCurrent directory contents:")
for item in os.listdir():
print(f"- {item}")
# Delete file
os.remove("new_test.txt")
print("\nFile deleted")
# Return to root directory and delete test directory
os.chdir("..")
os.rmdir(test_dir)
print(f"Directory deleted: {test_dir}")
# Execute test
test_filesystem()
4. Code Explanation
- Directory Operations: Create
<span>test_dir</span>directory and delete it after operations are complete - File Reading and Writing: Use
<span>with open()</span>to ensure files are closed properly - File Information: Get file size and other information using
<span>os.stat()</span> - Error Handling: Use
<span>try-except</span>to handle potential errors (e.g., directory already exists)
5. Notes
- The internal flash memory of the ESP32 is limited (usually about 4MB), so for large files, it is recommended to use an SD card
- Files must be closed after writing to ensure data is saved
- Ensure the directory is empty before deleting it
- Binary file operations require adding
<span>b</span>mode (e.g.,<span>wb</span>,<span>rb</span>)
6. with open(file_path, mode) as file_object:
In MicroPython (and Python), <span>with open()</span> is the standard way to handle file I/O, providing a safe and concise method for file operations.
6.1. Basic Syntax
with open(file_path, mode) as file_object:
# Use file_object for read/write operations
# ...
# File will be automatically closed here
- Key Points:
<span>with</span>statement automatically manages the opening and closing of files, ensuring files are closed even if an exception occurs.<span>file_object</span>is a reference to the opened file, which can be used for read/write operations.
6.2. File Open Modes
Common modes are as follows:
| Mode | Description | Example |
|---|---|---|
<span>r</span> |
Read-only mode (default) | <span>with open("data.txt", "r")</span> |
<span>w</span> |
Write mode (overwrites existing content) | <span>with open("output.txt", "w")</span> |
<span>a</span> |
Append mode (adds to the end of the file) | <span>with open("log.txt", "a")</span> |
<span>b</span> |
Binary mode (to be combined with other modes) | <span>with open("image.jpg", "rb")</span> |
<span>+</span> |
Read and write mode (to be combined with other modes) | <span>with open("data.txt", "r+")</span> |
6.3. File Reading Examples
6.3.1 Read Entire File Content
with open("test.txt", "r") as f:
content = f.read() # Read all content as a string
print(content)
6.3.2 Read Line by Line
with open("test.txt", "r") as f:
for line in f:
print(line.strip()) # Remove newline character at the end of the line
6.3.3 Read Specified Number of Bytes
with open("test.txt", "r") as f:
chunk = f.read(10) # Read 10 characters at a time
while chunk:
print(chunk)
chunk = f.read(10)
6.4. File Writing Examples
6.4.1 Overwrite Writing
with open("output.txt", "w") as f:
f.write("Hello, World!\n") # Write string
f.write("Second line content\n")
6.4.2 Append Writing
with open("output.txt", "a") as f:
f.write("Appended content\n")
6.4.3 Write Multiple Lines
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w") as f:
f.writelines(lines) # Directly write the list, need to add newline characters manually
6.5. Binary File Operations
Commonly used for images, audio, and other non-text files:
# Read binary file
with open("image.jpg", "rb") as f:
data = f.read()
# Write binary file
with open("new_image.jpg", "wb") as f:
f.write(data)
6.6. Advanced Usage: Simultaneous Read and Write
Using <span>r+</span> mode allows for simultaneous reading and writing of a file:
with open("data.txt", "r+") as f:
content = f.read() # Read first
f.seek(0) # Move file pointer back to the beginning
f.write("New beginning\n") # Overwrite original content
f.write(content) # Append original content
6.7. Why Use the <span>with</span> Statement?
Comparison with traditional writing:
# Writing without using with (must manually close the file)
f = open("test.txt", "r")
try:
content = f.read()
finally:
f.close() # Must ensure the file is closed
# Writing using with (automatically closes the file)
with open("test.txt", "r") as f:
content = f.read()
6.8. Common Error Handling
try:
with open("nonexistent.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("File does not exist!")
except Exception as e:
print(f"Other error: {e}")
<span>with open()</span> core advantages:
- Automatic Management of File Lifecycle: No need to manually call
<span>close()</span><span>.</span> - Exception Safety: Even if an exception is thrown in the code block, the file will be closed correctly.
- Concise and Readable: Code structure is clearer, reducing the risk of resource leaks.