Example code to create file, write to it, then display the files.
- import s the os library for working with files
- Opens (or creates if doesn’t’ exist) a file called “foo.txt”
- Then it writes the text “hello world” to the text file
- We then do a quick loop to concatenate all the files listed ( os.listdir() )
- Lastly, we scroll the files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from microbit import * import os sleep(1500) file = open("foo.txt", "w") file.write("hello world") file.close() s = "" allFiles = os.listdir() for str in allFiles : s+= str display.scroll(s ) |
A line-by line breakdown
1 |
import os |
Imports the library needed to work with the operating system.
1 |
file = open("foo.txt", "w") |
Opens up a file called “foo.txt” . If that file does not exist, then a file named “foo.txt” is created. We open the file with “w” , the ability to write to it.
1 2 |
file.write("hello world") file.close() |
Write the text “hello world” to the file and then close the file.
1 2 3 4 5 6 |
s = "" allFiles = os.listdir() for str in allFiles : s+= str display.scroll( s ) |
Creates an empty string s , stores a handles to all files from the os into a list using os.listDir() , then uses a foreach to loop over the list.
References: https://microbit-micropython.readthedocs.io/en/latest/filesystem.html