In this microbit tutorial we will check how to read the content of a file from the micro:bit file system, using MicroPython.
In this tutorial we will check how to read the content of a file from the micro:bit file system, using MicroPython. For an introduction on how to create and write content to a file, please check this previous tutorial.
We will start our code by writing a file to the file system, so we know that there is a file to read. Nonetheless, if you have already created a file on the file system by following the previous tutorial, you can skip this part and read that file.
As covered on the mentioned tutorial, we will first call the open function, passing as first input the name of the file and as second input the opening mode. We will call our file test.txt and we will open the file in write mode by passing “w” as second argument of the open function.
As output, the open function will return an object of class TextIO, which we will be using to write content to the file. So, we will call the write method on the mentioned object, passing as input a string with the content to write. We will just write a simple test string.
Finally, we will close the file by calling the close method on the TextIO object.
Now that we have the file on the file system, we will open it again and read its content. So, we will call the open method again, passing as input the name of the file. We don’t need to explicitly pass the opening mode since it defaults to reading .
Nonetheless, if we wanted to specify the mode argument, we would need to pass the value “r” to open the file in reading mode.
We will store the TextIO object returned by the open function in a variable, since we will need it to read the content of the file.
fileToRead = open("test.txt")
To read the content of the file, we simply need to call the read method on our object. As output, this method will return the content of the file. We will then print the content.
Note that, optionally, we can pass as input of the method the number of characters we want to read if we don’t want to read the whole file . Nonetheless, in our case, we will read the whole content.
content = fileToRead.read()
To finalize, we will close the file by calling the close method on our TextIO object.