0

$USD

$USD
TUTORIALS micro:bitMicroPython

micro:bit MicroPython Tutorial: Deleting a file from the file system

DFRobot Mar 11 2019 1180

In this microbit tutorial we will check how to delete a file from the micro:bit file system, using MicroPython.

Introduction

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.

The code

We will start our code by importing the os module, which will allow us to list all the files in the file system.

import os

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.

file = open("test.txt", "w")
file.write("test")
file.close()

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.

os.listdir()

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“.

os.remove("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.

os.listdir()

The final source code can be seen below.

import os
 
file = open("test.txt", "w")
file.write("test")
file.close()
 
os.listdir()
os.remove("test.txt")
os.listdir()

Testing the code

To test the code, simply run the previous script on your micro:bit board, using a tool of your choice. I’ll be using uPyCraft, a MicroPython IDE.

You should get an output similar to figure 1, which shows that, after the call to the remove function, the file is deleted from the file system, since it is no longer returned by the listdir function.



https://techtutorialsx.com/2019/02/12/microbit-micropython-deleting-a-file-from-the-file-system/