假設我有一個 csv 檔案,并且我更改了某些行的顏色。現在我有一個從 Internet 下載的新 csv 檔案。它有一些新行和一些舊行。我想在新檔案中找到唯一資料并將其附加到舊檔案中,同時保留任何顏色更改。
我可以做其他所有事情,但顏色正在重置。這就是我正在做的事情。
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')
這樣做會重置顏色。有沒有辦法保留這些資訊?
任何幫助是極大的贊賞。
uj5u.com熱心網友回復:
以前的答案包括合并 csv。然而,您的問題是關于著色資訊,到目前為止可能被忽略了,因為它沒有任何意義。如果您沉迷于著色 - 您需要與 csv 不同的格式。csv 不包含任何格式資訊:字體、顏色、列寬、行高等,這些都不是普通 csv 的一部分。
uj5u.com熱心網友回復:
如果您希望在 Python 中將新行追加到 CSV 檔案中,可以使用以下任何方法。
將所需行的資料分配到串列中。然后,使用 writer.writerow() 將此串列的資料附加到 CSV 檔案中。將所需行的資料分配到字典中。然后,使用 DictWriter.writerow() 將此字典的資料附加到 CSV 檔案中。
uj5u.com熱心網友回復:
我找到了一個適合您問題的示例。代碼如下:
# 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()
在運行上述代碼之前:
ID,NAME,SUBJECT
01,Henry,Python
02,Alice,C
運行上述代碼后:
ID,NAME,SUBJECT
01,Henry,Python
02,Alice,C
03,Smith,Science
在這里你可以找到上面的例子:
- https://www.delftstack.com/howto/python/python-append-to-csv/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/443067.html
