python对csv文件追加写入列数据

要在 Python 中追加列数据到 CSV 文件,可以使用以下步骤:

  1. 使用 csv 模块中的 reader() 函数读取 CSV 文件
  2. 使用 csv 模块中的 writer() 函数创建一个写入对象
  3. 使用写入对象的 writerow() 方法将数据写入 CSV 文件

示例代码如下:

import csv

# 读取 CSV 文件with open('original.csv', 'r') as f:
    reader = csv.reader(f)
    rows = [row for row in reader]

# 在第二列末尾添加一列数据
for row in rows:
    row.append('new column')

# 写入 CSV 文件
with open('modified.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)

上述代码会读取名为 original.csv 的 CSV 文件,在每一行的第二列末尾添加一列数据,然后将修改后的数据写入另一个 CSV 文件 modified.csv 中。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年8月8日
下一篇 2023年8月8日

相关推荐