Datasheet
Once the microSD card is mounted inside CircuitPython's filesystem you're ready to read and write data from it.
Reading and writing data is simple using Python's file operations like open, close, read, and write. The beauty of
CircuitPython and MicroPython is that they try to be as similar to desktop Python as possible, including access to files.
For example to create a file and write a line of text to it you can run:
Notice the with statement is used to create a context manager that opens and automatically closes the file. This is
handy because with file access you Python you must close the file when you're done or else all the data you thought
was written might be lost!
The open function is used to open the file by telling it the path to it, and the mode (w for writing). Notice the path is
under /sd, /sd/test.txt. This means the file will be created on the microSD card that was mounted as that path.
Inside the context manager you can access the f variable to operate on the file while it's open. The write function is
called to write a line of text to the file. Notice that unlike a print statement you need to end the string passed to write
with explicit carriage returns and new lines.
You can also open a file and read a line from it with similar code:
If you wanted to read and print all of the lines from a file you could call readline in a loop. Once readline reaches the
end of the file it will return an empty string so you know when to stop:
There's even a readlines function that will read all of the lines in the file and return them in an array of lines. Be careful
though as this means the entire file must be loaded into memory, so if the file is very large you might run out of
memory. If you know your file is very small you can use it though:
Finally one other very common file scenario is opening a file to add new data at the end, or append data. This works
exactly the same as in Python and the open function can be told you'd like to append instead of erase and write new
data (what normally happens with the w option for open). For example to add a line to the file:
with open("/sd/test.txt", "w") as f:
f.write("Hello world!\r\n")
with open("/sd/test.txt", "r") as f:
print("Read line from file:")
print(f.readline())
with open("/sd/test.txt", "r") as f:
print("Printing lines in file:")
line = f.readline()
while line != '':
print(line)
line = f.readline()
with open("/sd/test.txt", "r") as f:
lines = f.readlines()
print("Printing lines in file:")
for line in lines:
print(line)
© Adafruit Industries https://learn.adafruit.com/adafruit-adalogger-featherwing Page 30 of 36