How to Append a New Row to an Old CSV File in Python

Is there a way to append rows to an existing csv file while retaining the colors of rows?

The previous answers cover merging csv. Your question however was about coloring information which probably got ignored up to now, since it makes no sense.
If you are hung up on coloring - you need a different format than csv. csv does not include any formatting information: font, color, width of columns, height of rows, etc none of that is part of a normal csv.

Append a row from newly added csv file to the old one in python

So, with the following dataframes:

import pandas as pd

frame = pd.DataFrame(
{
"ID": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
"col1": [244, 65, 22, 97, 147, 89, 6, 88, 49, 34],
"col2": [122, 43, 12, 87, 100, 70, 3, 54, 18, 82],
}
)
print(frame)
# Output
ID col1 col2
0 A 244 122
1 B 65 43
2 C 22 12
3 D 97 87
4 E 147 100
5 F 89 70
6 G 6 3
7 H 88 54
8 I 49 18
9 J 34 82
old_csv = pd.DataFrame(
{
"Time Point": [1],
"A": [9],
"B": [14],
"C": [219],
"D": [54],
"E": [99],
"F": [78],
"G": [5],
"H": [77],
"I": [65],
"J": [44],
}
)
print(old_csv)
# Output
Time Point A B C D E F G H I J
0 1 9 14 219 54 99 78 5 77 65 44

You could try this:

new_row = pd.DataFrame(frame.loc[:, "col2"]).T.rename(
columns={
k: v for k, v in enumerate(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"])
}
)

new_csv = pd.concat([old_csv, new_row]).reset_index(drop=True)
new_csv.at[len(old_csv), "Time Point"] = (
len(old_csv) + 1
)
new_csv["Time Point"] = new_csv["Time Point"].astype(int)

print(new_csv)
# Ouput
Time Point A B C D E F G H I J
0 1 9 14 219 54 99 78 5 77 65 44
1 2 122 43 12 87 100 70 3 54 18 82

Append Data to the end of a row in a csv file (Python)

I advise you to use pandas module and read_csv method.

You can use the following code for instance :

data = pandas.read_csv("your_file.csv")
row = data.iloc[0].to_numpy()
row.append(['wtire1','wtire2','wtire3','wtire4'])

How to add data to existing rows of a CSV file?

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')

How to append row into csv file through python with commas separating new row and previous

If you look at the documentation, when they open the file they put a newline argument.

    import csv
with open('eggs.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile)
for row in spamreader:
print(', '.join(row))
    import csv
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

For the part where you a reading the row from the file, you should check if each row contains the 4 items you need.



Related Topics



Leave a reply



Submit