'How to add data to existing rows of a CSV file? [duplicate]

I have already an existing CSV file that I am accessing and I want to append the data to the first row, but it writes data at the end of the file.

What I am getting:

enter image description here

But I want the data to append like this:

enter image description here

Code I have done so far:

import CSV

with open('explanation.csv' , 'a', newline="") as file:
    myFile = csv.writer(file)
    myFile.writerow(["1"])


Solution 1:[1]

What you're actually wanting to do is replace data in an existing CSV file with new values, however in order to update a CSV file you must rewrite the whole thing.

One way to do that is by reading the whole thing into memory, updating the data, and then use it to overwrite the existing file. Alternatively you could process the file a row-at-a-time and store the results in a temporary file, then replace the original with the temporary file when finished updating them all.

The code to do the latter is shown below:

import csv
import os
from pathlib import Path
from tempfile import NamedTemporaryFile


filepath = Path('explanation.csv')  # CSV file to update.

with open(filepath, 'r', newline='') as csv_file, \
     NamedTemporaryFile('w', newline='', dir=filepath.parent, delete=False) as tmp_file:

    reader = csv.reader(csv_file)
    writer = csv.writer(tmp_file)

    # Replace value in the first column of the first 5 rows.
    for data_value in range(1, 6):
        row = next(reader)
        row[0] = data_value
        writer.writerow(row)

    writer.writerows(reader)  # Copy remaining rows of original file.

# Replace original file with updated version.
os.replace(tmp_file.name, filepath)

print('CSV file updated')

Solution 2:[2]

You could read in the entire file, append your rows in memory, and then write the entire file:

 def append(fname, data):
        with open(fname) as f:
            reader = csv.reader(f)
            data = list(reader) + list(data)
        with open(fname, 'w') as f:
            writer = csv.writer(f)
            writer.writerows(data)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 DontDownvote