Uncategorized

CSV Python does not modify the corresponding column for a row


# Dump stop data to CSV
def write_stops(data_machines):
    
    # Check if the file is empty
    if not os.path.isfile('stops.csv'):
        # Write the header only if the file is empty
        with open('stops.csv', 'w', newline="", encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=stop_fields)
            writer.writeheader()

    # Create a variable to store stop records
    stop_records = []

    # Iterate over machine data
    for machine_dict in data_machines:
        # If there is a stop, add a new record to the DataFrame
        if machine_dict['id_stop'] is not None:
            # print(f"Comparing machine {machine_dict['Machine']}")

            existing_stop_id = machine_dict['id_stop']
            with open('stops.csv', 'r+', newline="", encoding='utf-8') as f:
                csv_reader = csv.DictReader(f)

                # Flag to indicate if the record was found
                found = False

                # Iterate over each row in the 'id_stop' column
                for row in csv_reader:
                    if row['id_stop'] == existing_stop_id:
                        print(f"Record found {existing_stop_id}. Updating Down Description to {machine_dict['Down Description']}")
                        # Update the 'Down Description' column with machine_dict['Down Description'] corresponding to the row
                        row['Down Description'] = machine_dict['Down Description']
                        found = True
                        break

                # If no record is found, create one at the end of the .csv file
                if not found:
                    new_record = {
                        'id_stop': machine_dict['id_stop'],
                        'Down Description': machine_dict['Down Description']
                    }
                    stop_records.append(new_record)
                    print(f"No record found for {machine_dict['Machine']} id_stop {machine_dict['id_stop']}")

    # Write stop records to the CSV file
    with open('stops.csv', 'a', newline="", encoding='utf-8') as f:
        csv_writer = csv.DictWriter(f, fieldnames=stop_fields)
        
        for record in stop_records:
            csv_writer.writerow(record)

I’ve asked ChatGPT to translate the code into English because I am Spanish. There may be a typographical error. The code compiles and performs its function. When there is no corresponding record for the id_stop, it creates one, and in the next iteration, it finds it by traversing the stops.csv file. It prints correctly. The problem I have is that it does not overwrite the corresponding Down Description column for the found row. I’ve tried all possible permissions, but nothing. Any ideas?

It performs the entire function correctly, and it also finds the row when traversing the CSV. The CSV has only 2 columns, id_stop and Down Description, but the Down Description field is not overwritten with the current value. In each iteration, it prints the value, and it appears correct, but it does not overwrite it in the CSV.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *