這是有問題的代碼:
def write_to_csv(current_time_in_utc: datetime, time: int, start_latitude: float, stop_latitude: float, current_lat=None, step=None) -> None:
if not exists('/app/pan_tilt_unit/value_recording/position_values.csv'):
create_csv()
# Use some memoization here so we don't have to calculate the step each loop
# Should probably check if accessing a dict value by key is faster than the simple calculation - might benchmark it
if not step:
step = approximate_position_steps(start_latitude, stop_latitude, time)
step_for_memoization[step] = step
if not current_lat:
current_lat = start_latitude
if time >= 0:
with open('/app/pan_tilt_unit/value_recording/position_values.csv', 'a') as csv_file:
csv_writer = writer(csv_file)
csv_writer.writerow([current_time_in_utc, current_lat])
logger.info("Writing values to file.")
sleep(1)
write_to_csv(datetime.utcnow(), time-1, start_latitude, stop_latitude, current_lat=current_lat step, step=step_for_memoization[step])
else:
logger.debug("Finished writing values to file.")
step_for_memoization.clear()
return
這是一個示例輸出:
time_in_UTC,current_latitude,current_longitude
2022-04-01 03:23:13.166506,142.34200000000007
2022-04-01 03:23:12.165016,141.59500000000006
2022-04-01 03:23:11.162850,140.84800000000004
2022-04-01 03:23:10.161289,140.10100000000003
2022-04-01 03:23:09.159162,139.354
2022-04-01 03:23:08.156691,138.607
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.
uj5u.com熱心網友回復:
從 中取消遞回呼叫with open,以便緩沖的寫入行在遞回呼叫之前而不是在遞回呼叫回傳之后實際重繪 /寫入檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/455916.html
