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
Python Ctypes - Loading Dll Throws Oserror: [Winerror 193] %1 Is Not a Valid Win32 Application
In Matplotlib, What Does the Argument Mean in Fig.Add_Subplot(111)
Parsing Boolean Values with Argparse
How to Get Different Colored Lines for Different Plots in a Single Figure
How to Get a List of All the Duplicate Items Using Pandas in Python
Pandas: Drop a Level from a Multi-Level Column Index
Sharing a Result Queue Among Several Processes
How to Create a Reference to a Variable in Python
Why Is a List Comprehension So Much Faster Than Appending to a List
Show Default Value for Editing on Python Input Possible
How to Prevent Numbers Being Changed to Exponential Form in Python Matplotlib Figure
Combine Two Pandas Data Frames (Join on a Common Column)
Sort List of Lists Ascending and Then Descending
Negative Integer Division Surprising Result
How to Log While Using Multiprocessing in Python
Change the Color of Text Within a Pandas Dataframe HTML Table Python Using Styles and CSS