How to Add Column to CSV in Python
To add a new column of data to a CSV file in Python, you can follow these steps:
- Firstly, read the CSV file and load the data into a list.
import csv
with open('file.csv', 'r') as file:
reader = csv.reader(file)
data = list(reader)
- Next, perform an operation on each row in the data list, adding new column data to the end of each row.
for row in data:
# 添加新的列数据
new_column_data = 'new_data'
row.append(new_column_data)
- Finally, write the updated data list back to the CSV file.
with open('file.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
In this way, you can successfully add a new column of data to the CSV file.