In this microbit tutorial we will check how to get the size of a file on the micro:bit file system, using MicroPython.
In this tutorial we will check how to get the size of a file on the micro:bit file system, using MicroPython.
The first thing we will do is importing the os module, which will expose the function we need to get the size of a file from the file system.
Then we are going to create a new file on the file system, to make sure we have one to obtain the size. The procedure to create a file is detailed on this previous post. If you already have a file on the file system, you can use it instead if you want.
We will create a file called “test.txt” and write a simple test string to it. Note that the write method that we are going to use to write the content to the file returns as output the number of characters written .
So, we are going to store that value in a variable and print it, to later compare it against the value we will obtain when getting the file size using an os module function.
After creating the file, we can obtain its size, in bytes, by calling the size function from the os module. As input, this function receives the name of the file. As output, it returns the size of the file, in bytes .
We will directly print the value returned by the size function.
To test the code, simply run it on your micro:bit board using a tool of your choice. In my case, I’ll be using a MicroPython IDE called uPyCraft.
Upon running the script, you should get a result similar to figure 1. As can be seen, it shows the number of characters written to the file after calling the write method, and the size of the file obtained with a call to the size function from the os module.
Both values match because each of the characters we have written to the file can be represented by a single byte.