首页 > 解决方案 > 将 csv 值复制到另一个 csv

问题描述

我正在复制一个 csv 文件的内容并将其写入另一个文件,以便稍后对其进行修改,但无法弄清楚简单的解决方案是什么。我想我可以在复制内容时保持输入csv_file和输出writer文件打开,不知道这是否是个好主意。我的代码

import csv, os

file_path = 'path/to/file.csv'
output_path = os.path.dirname(os.path.abspath(file_path)) + '/'

with open(file_path) as csv_file:
    data_source = csv.reader(csv_file, delimiter=',')
    with open(output_path + 'results.csv', 'w', newline='') as writer:
        for line in data_source:
            writer.writerow(line)

这是我得到的错误:

AttributeError: '_io.TextIOWrapper' object has no attribute 'writerow'

标签: pythonpython-3.xcsv

解决方案


你认为是作家的对象不是。相反,您应该单独构建编写器。

with open(file_path) as csv_file:
    data_source = csv.reader(csv_file, delimiter=',')
    with open(output_path + 'results.csv', 'w', newline='') as results_file:
        data_sink = csv.writer(results_file) #This is the important line
        for line in data_source:
            data_sink.writerow(line)

推荐阅读