Adapted and simplified from Franck Albinet's exercises available here. Also presented by NSRC at APRICOT 2018.
...
Code Block | ||||
---|---|---|---|---|
| ||||
import time year, month, day, hour, minute, second, ms, dayinyear = time.localtime() nameCsv = '/flash/log/acq' nameCsv = nameCsv + '{:04d}'.format(year) nameCsv = nameCsv + '{:02d}'.format(month) nameCsv = nameCsv + '{:02d}'.format(day) nameCsv = nameCsv + '{:02d}'.format(hour) nameCsv = nameCsv + '{:02d}'.format(minute) nameCsv = nameCsv + '{:02d}'.format(second) nameCsv = nameCsv + 'list.csv' |
A second approach more succinct would be to take advantage of Python list comprehensions:
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.