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:

  1. 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)
  1. 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)
  1. 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.

bannerAds