Suppose I have a csv file and I've changed colors of some rows. Now I have a new csv file that I am downloading from the internet. It has some new rows and some old. I want to find the unique data in the new file and append it to the old file while retaining any color changes.
I am able to do everything else but the colors are getting reset. Here is what I'm doing.
old_data = pd.read_csv('old_data.csv')
new_data = pd.read_csv('new_data.csv')
unique_data = new_data[~new_data['Booking Reference'].isin(old_data['Booking Reference'])]
unique_data.to_csv('old_data.csv', 'a')
Doing this way resets the colors. Is there a way to retain that information?
Any help is greatly appreciated.
CodePudding user response:
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.
CodePudding user response:
If you wish to append a new row into a CSV file in Python, you can use any of the following methods.
Assign the desired row’s data into a List. Then, append this List’s data to the CSV file using writer.writerow(). Assign the desired row’s data into a Dictionary. Then, append this dictionary’s data to the CSV file using DictWriter.writerow().
CodePudding user response:
I found an example that fit your problem. Code is as follow:
# Pre-requisite - Import the writer class from the csv module
from csv import writer
# The data assigned to the list
list_data=['03','Smith','Science']
# Pre-requisite - The CSV file should be manually closed before running this code.
# First, open the old CSV file in append mode, hence mentioned as 'a'
# Then, for the CSV file, create a file object
with open('CSVFILE.csv', 'a', newline='') as f_object:
# Pass the CSV file object to the writer() function
writer_object = writer(f_object)
# Result - a writer object
# Pass the data in the list as an argument into the writerow() function
writer_object.writerow(list_data)
# Close the file object
f_object.close()
Before running the above code:
ID,NAME,SUBJECT
01,Henry,Python
02,Alice,C
After running the above code:
ID,NAME,SUBJECT
01,Henry,Python
02,Alice,C
03,Smith,Science
Here you can find the above example: