如何在现有的csv文件中插入列?

时间:2020-01-18 15:43:58

标签: python csv

我是Python的新手,并且需要一些有关如何将列插入包含数据=今天日期的现有csv文件中的说明。

感谢您提供的任何指导/见解。

提前谢谢! AJ

1 个答案:

答案 0 :(得分:0)

您应该在Python中使用csv进行一些后台搜索。有很多不错的文章/教程。大多数情况下,csv模块都是为了方便和功能而使用,但这不是必需的。

要修改的基本架构(如上面的注释中所述)是:

  • 打开您要阅读的文件
  • 打开另一个保存修改后的结果的文件
  • 逐行浏览正在读取的文件
  • 根据需要计算新值,或将其附加到行中
  • 将其写入新文件
  • 关闭两个文件

以下是使用csv模块的示例:

import csv
input_file = 'data.csv'
output_file = 'data_mod.csv'

with open(output_file, 'w') as target:
    target_writer = csv.writer(target)

    # open the source
    with open(input_file, 'r') as source:
        source_reader = csv.reader(source)
        # now both are "open and ready"
        # fix the header row, assuming there is one by reading 1 line
        header = source_reader.__next__()
        # csv reader returns a list for the rows read, so header is a list,
        # we can just add to it
        header.append('sum')
        # write to the modified file
        target_writer.writerow(header)
        # now use loop to update all remaining rows
        for row in source_reader:
            sum = int(row[0]) + int(row[1])
            row.append(sum)
            target_writer.writerow(row)
# if you use the 'with' command structure, it will close the files automatically
print('done')

原始文件:

value 1,value 2
1,2
3,4
-2,2

修改后的文件data_mod.csv:

value 1,value 2,sum
1,2,3
3,4,7
-2,2,0