How to Create, Read and Write to File with Microbit

Example code to create file, write to it, then display the files.

  1. import s the os  library for working with files
  2. Opens (or creates if doesn’t’ exist) a file called “foo.txt”
  3. Then it writes the text “hello world” to the text file
  4. We then do a quick loop to concatenate all the files listed (os.listdir()  )
  5. Lastly, we scroll the files.
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 )

file-system-animated-gif.gif

A line-by line breakdown

import os

Imports the library needed to work with the operating system.

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.

file.write("hello world")
file.close()

Write the text “hello world” to the file and then close the file.

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