0

$USD

$USD
TUTORIALS micro:bitMicroPython

micro:bit MicroPython file system: Getting a file size

DFRobot Mar 11 2019 1075

In this microbit tutorial we will check how to get the size of a file on the micro:bit file system, using MicroPython.

Introduction

In this tutorial we will check how to get the size of a file on the micro:bit file system, using MicroPython.

The code

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.

import os

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 [1].

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.

file = open("test.txt", "w")
 
writtenCharacters = file.write("Hello World!!!")
print(writtenCharacters)
 
file.close()

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 [2].

We will directly print the value returned by the size function.

print(os.size("test.txt"))

The final complete code can be seen below.

import os
 
file = open("test.txt", "w")
writtenCharacters = file.write("Hello World!!!")
 
print(writtenCharacters)
 
file.close()
 
print(os.size("test.txt"))

Testing the code

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.


https://techtutorialsx.com/2019/02/26/microbit-micropython-getting-file-size/

References
[1] https://microbit-micropython.readthedocs.io/en/latest/filesystem.html#BytesIO.write

[2] https://microbit-micropython.readthedocs.io/en/latest/os.html#os.size

Related Posts
Micro:bit MicroPython: reading a file from the file system
Micro:bit MicroPython: creating a file in the filesystem