In this microbit tutorial we will check how to delete a file from the micro:bit file system, using MicroPython.
In this microbit tutorial we will check how to delete a file from the micro:bit file system, using MicroPython. For an introductory tutorial on how to write a file to the file system, please check here.
We will start our code by importing the os module, which will allow us to list all the files in the file system.
Then, we will create a file in the file system so we make sure that we have one to delete. If you have already created a file by following one of the previous tutorials, then you can use that to delete instead.
So, in order to create the file, we will call the open function, passing as first input the name of the file and as second the opening mode. We will call the file “text.txt” and we will pass “w” as opening mode, so it is opened for writing.
Then, we will write some content to the file by calling the write method on the TextIO object returned by open function call. As input, we will pass the content to write, which will be a simple testing string.
Then, we will close the file with a call to the close method.
Now that we have created the file, we will confirm its existence on the micro:bit file system by calling the listdir function of the os module. The returned list should contain the “test.txt” file.
Then, to delete the file, we will call the remove function from the os module. This function will remove from the file system the file with the name we pass as argument. So, in our case, we will pass the name of our previously created file: “test.txt“.
To finalize, we will list again all the files in the file system, with a call to the listdir function from the os module.