Here is the code in question first:
JavaScript
x
25
25
1
def write_to_csv(current_time_in_utc: datetime, time: int, start_latitude: float, stop_latitude: float, current_lat=None, step=None) -> None:
2
if not exists('/app/pan_tilt_unit/value_recording/position_values.csv'):
3
create_csv()
4
5
# Use some memoization here so we don't have to calculate the step each loop
6
# Should probably check if accessing a dict value by key is faster than the simple calculation - might benchmark it
7
if not step:
8
step = approximate_position_steps(start_latitude, stop_latitude, time)
9
step_for_memoization[step] = step
10
11
if not current_lat:
12
current_lat = start_latitude
13
14
if time >= 0:
15
with open('/app/pan_tilt_unit/value_recording/position_values.csv', 'a') as csv_file:
16
csv_writer = writer(csv_file)
17
csv_writer.writerow([current_time_in_utc, current_lat])
18
logger.info("Writing values to file.")
19
sleep(1)
20
write_to_csv(datetime.utcnow(), time-1, start_latitude, stop_latitude, current_lat=current_lat+step, step=step_for_memoization[step])
21
else:
22
logger.debug("Finished writing values to file.")
23
step_for_memoization.clear()
24
return
25
Here is an example output:
JavaScript
1
8
1
time_in_UTC,current_latitude,current_longitude
2
2022-04-01 03:23:13.166506,142.34200000000007
3
2022-04-01 03:23:12.165016,141.59500000000006
4
2022-04-01 03:23:11.162850,140.84800000000004
5
2022-04-01 03:23:10.161289,140.10100000000003
6
2022-04-01 03:23:09.159162,139.354
7
2022-04-01 03:23:08.156691,138.607
8
Why is the csv being written in reverse? The time stamp should be going from 03:23:08 to 03:23:13, but it’s not.. I’m thinking it’s maybe because I’m calling this recursively? But not totally sure. the ‘a’ in the with open() is for ‘append’, so logically it should just append each value one after the other as they’re returned.
Advertisement
Answer
Unindent the recursive call out of the with open
, so that the buffered written row is actually flushed/written to the file before the recursive call instead of after the recursive call returned.