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.


A line-by line breakdown

Imports the library needed to work with the operating system.

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.

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

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.