micro:bit basic data logging 1

This is a first program to write text to a file and read the contents of the file again

A first program to write text to a file and read the contents afterwards

There are three parts to writing data to file:
– opening the file
– writing data
– closing the file afterwards

Line 3: opening the file
The ‘open’ commands says open a file with name “storm.txt”; the w indicates the file is to be opened to write, and the function open returns a “file handle” (which is the reference to the file, used by write and close operations with the file, which we store in variable fw)

Lines 4-6 writing data to the file.
This writes three lines of text to the file. At the end of each lines we add “\n” (which indicates end of line)

Line 7 closing the file.
Sometimes you can get away without doing this, but the computer may not like it, and unexpected things can happen.

Lines 9 to 16 Read from the File
Again, there are three parts to reading from a file:
– opening the file
– reading data
– closing the file afterwards
Again, note the use of the “file handle”, which, this time, we store in variable fr

There is an important difference when reading from a file – how do we know when we have read everything? In this case, we know there are 3 lines, but that could easily be changed.

Line 9 Here we have a variable ‘eof’ to indicate that the end of the file has been reached (eof is an abbreviation for end of file, and often used in computing).
Lines 14 – 15: It seems reasonable that if we read from the file and no text is returned – that is the end of the file, and eof is set to be True

Line 10 opens the file. Note it is the same file as we had on line 5 , and this time, we use “r” to indicate we are reading the file
Line 12 – 13 reads a line of text from the file and prints it out. Remember on lines 6-8 “\n” was added to the denote the end of the line
line 16 closes the file

Instructions for Use:
Flash to the micro:bit and it will run and display the output

Output from program


The program as a text file can be downloaded here

There is a further program to read and write data to a file

This has been written as an example of to how to use files on the micro:bit, comments and suggestions to improve this would be welcome. Code can be freely downloaded, adapted and used. But if a school could mention our software for primary/elementary students we would be very grateful stormeducational.co.uk (with free online demos at stormedapps.co.uk).

Leave a comment