Adapted and simplified from Franck Albinet's exercises available here. Also presented by NSRC at APRICOT 2018.
...
You will learn how to: access and operate device's file system; create and write a file in the flash
folder; mount and use an SD
card as an alternative; handle files safely using with
statement; generate programmatically time stamped log file names; make your code robust and flexible with try ... except
statement.
...
- a LoPy or WiPy module
- a microUSB cable
- a development PC
The source code is in the src/micro-sd
directoryavailable here.
Folder structure
The folder tree is the following:
...
Let's explore and navigate this folder structure interactively. Connect to a Lopy via the Atom console and import . If there is a program running, use Control-C to stop it. Import the basic operating system module (os): import os
.
...
Code Block | ||||
---|---|---|---|---|
| ||||
base = '/flash/log/acq/' time_stamp = ''.join(['{:02d}'.format(i) for i in time.localtime()][:6]) name = base + time_stamp + 'list.csv' |
Let's unpack this second implementation:
Code Block | ||||
---|---|---|---|---|
| ||||
time.localtime() |
outputs a tuple (1970, 1, 1, 0, 21, 40, 3, 1)
representing year, month, ...
- formatting integer to string with list comprehension
Code Block | ||||
---|---|---|---|---|
| ||||
['{:02d}'.format(i) for i in time.localtime() |
outputs ['1970', '01', '01', '00', '24', '05', '03', '01']
We keep only year, month, day, hour, min., sec. by slicing the list:
Code Block | ||||
---|---|---|---|---|
| ||||
['{:02d}'.format(i) for i in time.localtime()][:6] |
- last we join the list to a single string
Code Block | ||||
---|---|---|---|---|
| ||||
''.join(['{:02d}'.format(i) for i in time.localtime()][:6]) |
outputs: '19700101002920'
We can now simply concatenate this substring with a prefix and suffix and that's done.
As it is a quite frequent operation, we could even encapsulate it in an helper function as below:
Code Block | ||||
---|---|---|---|---|
| ||||
def get_log_filename(prefix, suffix): time_stamp = ''.join(['{:02d}'.format(i) for i in time.localtime()][:6]) return prefix + time_stamp + suffix |
and use it when required: get_log_filename('/flash/log/acq', 'list.csv')
Exercise
Write a script writing a file named "log.csv"
in /flash/log/
folder so that:
- if the user pushes the button the pressing time and an incremented counter is saved;
- it the counter reaches 10, LED is switched on.