Adapted and simplified from Franck Albinet's exercises available here. Also presented by NSRC at APRICOT 2018.
...
Let's explore and navigate this folder structure interactively. Connect to a Lopy via the Atom console . If there is a program running, use Control-C to stop it. and upload the source code for this exercise.
Import the basic operating system module (os): import os
.Once imported: to know you current working directory:
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
import os # to find you current working directory: os.getcwd() |
...
## most probably the |
...
/flashfolder # to list folders and files in your current working directory: os.listdir() |
...
# to create a new folder/directory named "log": os.mkdir('log'); ... |
Take a look at os module documentation for a full list of methods.
Now notice that if you list the files and folders under the root
folder: os.listdir('/'),
you get only the flash
directory. There is no SD
card mounted yet.
Writing
In the simplest case, to create and write a new file:
...
Once open, you get a file object to play with and hence can start writing data in it:python
Code Block | ||||
---|---|---|---|---|
| ||||
f.write('Testing write operations in a file.') |
Then you need to close the file to free up any system resources taken up by the open file. After calling f.close()
, attempts to use the file object will automatically fail.
...
For instance to read the file just created, you can use the following syntax:
Code Block | ||||
---|---|---|---|---|
| ||||
with open('log/my_first_file.log', 'r') as f:
f.readall() |
This is much cleaner and safer.
...
outputs a tuple (1970, 1, 1, 0, 21, 40, 3, 1)
representing year, month, ...
...
Code Block | ||||
---|---|---|---|---|
| ||||
# formatting integer to string with list comprehension
['{:02d}'.format(i) for i in time.localtime()
|
outputs ['1970', '01', '01', '00', '24', '05', '03', '01']
Code Block | ||||
---|---|---|---|---|
| ||||
# We keep only year, month, day, hour, min., sec. by slicing the list: |
...
Code Block | ||||
---|---|---|---|---|
| ||||
['{:02d}'.format(i) for i in time.localtime()][:6]
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
# last we join the list to a single string
''.join(['{:02d}'.format(i) for i in time.localtime()][:6])
|
...