Skip to content
Advertisement

Python: values written to csv file are in reverse order?

Here is the code in question first:

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

Here is an example output:

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.

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement