MicroPython: Reading & Writing Files

Contents

This is a tutorial that teaches the basic principles of reading and writing to files on microcontroller boards running MicroPython firmware.

Opening a File

Whenever dealing with a file for reading or writing, the first task is to create a file object.


Syntax:
with open('file_name', mode='w') as <variable_name>:
    ...perform some file operations...

Purpose:
  Returns a file object with the variable
  name <variable_name> in a runtime context.

Where:
  'file_name' : The name of the file enclosed in
                single or double quotes.

  mode : One of 'w', 'x', 'a' or 'r'.
         The flag 'b' can be added to
         indicate a binary file.

Example:
# Open a file 'hello.txt' for writing
# in the '/flash' directory.
# Returns the file object as the variable 'f'.
with open("/flash/hello.txt", mode="w") as f:
          

As stated above this syntax returns a file object (also known as a file handle  or stream) in a runtime context under the control of a context manager. This is the modern accepted best practise for a variety of reason:

  • Automatic resource cleanup: The file is guaranteed to be closed automatically once the program flow exits the with block. There is no need to call close() manually.
  • Exception safety: In the event of an exception being raised cleanup always happens preventing files from being left open in a potentially corrupted state.
  • Simpler code: Using a with statement replaces verbose try...finally blocks, making the code more concise and easier to read and maintain.
File Names

The file can be opened on the microcontroller's internal filesystem e.g. data_file.txt in the first level directory data :

  • "/flash/data/data_file.txt"

If a microSD card is mounted then the equivalent path name on the card filesystem will most likely be:

  • "/sd/data/data_file.txt"
Modes

The file can be opened in any of the following modes:

  • 'w' : Write mode. Creates the file if it doesn't exist. Overwrites an existing file. This is the default mode.
  • 'a' : Append mode. Creates the file if it doesn't exist. Writes data always at the file's end.
  • 'x' : Exclusive create mode. Creates new file if the file doesn't exist. An exception is thrown if the file exists.
  • 'r' : Read mode.
  • 'b' : Binary flag. Combine with one of the other modes for binary files e.g. 'rb'

File Object Methods

There aren't many file methods and they're all simple to use.

Sequential file access
  • write(string) : Writes the specified string (or bytes object in binary mode) to the file. It does not add a newline character automatically.
  • read(size=-1) : Reads at most size bytes (or characters in text mode) from the file and returns them as a string or bytes object. If size is omitted or negative, it reads the entire content of the file.
  • readline(size=-1) : Reads one entire line from the file, including the newline character (\n), and returns it as a string. If size is provided, it reads at most size bytes/characters of the line.
  • readlines() : Reads all lines from the file and returns them as a list of strings, where each string represents a line.
Random file access

All of the above methods provide sequential file access. MicroPython does allow random access on files. There are two methods for this purpose:

  • tell() : Returns the current position of the file pointer. Like most indexing in MicroPython, the file pointer is zero indexed i.e. the first byte in the file has an index of 0.
  • seek(offset, [whence=0]) : Changes the current file position. offset specifies the number of bytes to move, and whence defines the reference point (0 for beginning, 1 for current position, 2 for end).

Examples

All of the following examples read and write files to the internal filesystem /flash.

Example 1: A simple example that writes three lines to a text file and reads it back with the read() method.


import math

with open('/flash/file.txt', 'w') as f:
    f.write('First line\n')
    f.write('Second line\n')   
    f.write('Pi = ' + str(math.pi) + '\n')

with open('/flash/file.txt', 'r') as f:
    print(f.read())

Output:
First line
Second line
Pi = 3.1415928  
          

Example 2: This example reads back the contents of the file from Example 1 as a list of strings with the readline() method.


with open('/flash/file.txt', 'r') as f:
    print(f.readlines())

Output:
['First line\n', 'Second line\n', 'Pi = 3.1415928\n'] 
          

Example 3: This example appends another line to the file from Example 1 then reads back the contents of the file using the read() method.


with open('/flash/file.txt', 'a') as f:
    f.write('Appended line')

with open('/flash/file.txt', 'r') as f:
    print(f.read())  

Output:
First line
Second line
Pi = 3.1415928
Appended line
          

Example 4: This example demonstrates random access on a binary file.


# Write some binary data to a file
data = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08"

with open('/flash/file.bin', 'wb') as f:
    f.write(data)
 
# Open the file for binary read
with open('/flash/file.bin', 'rb') as f:
    # Move the file pointer to the 6th byte
    f.seek(5) # Remember, file pointer is zero indexed!
    print('File pointer:', f.tell())
    # Read three bytes from here
    print(f.read(3))
    print('File pointer:', f.tell()) 

Output:
File pointer: 5
b'\x05\x06\x07'
File pointer: 8