python - 将 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'
解决方案
你认为是作家的对象不是。相反,您应该单独构建编写器。
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)
推荐阅读
- java - 如何在不使用任何整数变量的情况下在按钮单击时在 Textview 上应用 If Else?
- solr - 向 Carrot2 WAR 文件添加身份验证
- android - 将枚举与数字一起使用
- python - openCV的conda错误-找不到符号
- amazon-web-services - 将 Amazon S3 用于客户图像和缩略图
- powershell - PowerShell - 如果是特定字符,则删除第一个字符
- api - 使用 GMail API 如何查看帐户上是否有现有手表?
- php - 为什么我不能将当前日期保存在 mysql 的数据库中?
- oracle-adf - 如何通过托管 bean 以编程方式提交?
- cassandra - Cassandra 不可预测的失败取决于 WHERE 子句