python - Python:将顶行的标题附加到 CSV 文件
问题描述
我正在运行将新数据共同添加到现有 CSV 文件的脚本,并且我想在添加新数据时附加其他标题。例如,以下是原始 CSV 的结构:
user_id, text, text_number
0, test text A, text_0
1,
2,
3,
4,
5, test text B, text_1
我想添加额外的标题,如下所示:
user_id, text, text_number, field_1, field_2, field_3, field_4
0, test text A, text_0
1,
2,
3,
4,
5, test text B, text_1
下面的代码添加了标头,但只是将标头附加到文件的末尾。
import csv
header = ["field_1", "field_2", "field_3", "field_4"]
with open('test.csv', 'a', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
有没有办法构造上面的代码以将新标题附加到 row 0
?非常感谢所有帮助。
解决方案
简单的文件和字符串处理:
with open('input.csv') as infile:
text = infile.read()
header = ["field_1", "field_2", "field_3", "field_4"]
with open('output.csv', 'w') as outfile:
# join the headers into a string with commas and add a newline
outfile.write(f"{','.join(header)}\n")
outfile.write(text)
推荐阅读
- python - 如何使用 eventfilter 和 installeventfilter 方法?
- python - pyinstaller 与 python argparse -h 不兼容
- r - `[<-`(`*tmp*`, f, k, value = mean(knn.pred != test.setY)) 中的错误:下标越界
- node.js - 每次我在我的项目上运行 npm install 时,node-gyp 都会抛出这个错误
- macos - SwiftUI MacOS 菜单彻底坏掉了?
- sql - Oracle PL-SQL:使用多种方法通过动态 SQL 生成唯一条件
- python - 如何将部分数据帧转换为矢量
- python - 使用下拉 @ plotly 更改等值线符号系统
- node.js - 无服务器框架上的 serverless.yml 文件是什么?
- c++ - 用int_fastN_t代替intN_t好不好