python - 我将如何修改它以添加一列?
问题描述
我有 csv 文件。它没有列名。我需要在行首添加新列。我的意思是数组[0]。我是新来的。请帮我。
这是我拥有的 csv 文件
1,100,303,619,figure
338,162,143,423,text
85,768,554,39,text
504,164,24,238,subtitle
我只想像这样添加新列记录
Record_01,98,87,544,396,figure
Record_02,98,488,91,48,caption
Record_03,98,568,142,254,figure
Record_04,97,834,8,6,page
我试过这个代码它不起作用。它不显示错误消息。但这并没有改变任何东西。
key = []
for row, Record in enumerate(key):
print('Record_{}'.format(row, Record))
row.append(row[0])
key.appen(row)
with open('csvfiles', 'r') as csvinput:
with open('csvfiles', 'w') as csvoutput:
writer = csv.writer(csvoutput, delimiter=',')
writer.writerow[key]
非常感谢任何答案。
解决方案
根据您自己删除的答案,您已经很接近了。变化在于writer.writerows(data)
您可以迭代行并更改每行以具有额外的条目,而不是您。
import csv
#load the file
with open('00001.csv') as input_file:
#read the input csv file
reader = csv.reader(input_file)
data = [line for line in reader]
#load the the output file
with open('00001.csv','w') as output_file:
writer = csv.writer(output_csvfile)
#add the column name
writer.writerow(["X", "Y", "Width", "Height", "Tag"])
# for each line including indices
for i,line in enumerate(data, start=1):
# insert extra entry at beginning of line (index 0)
line.insert(0,"Record_{}".format(i))
# write the row.
writer.writerow(line)
推荐阅读
- c# - DateTime 日、月、年的标准格式
- javascript - 在 node.js 中设置应用程序生产和开发模式
- c++ - 赋值运算符链接中的 const 关键字
- php - 在 PHP 中限制对 setter 的访问?
- vb.net - VB.Net - 无法启用约束。一行或多行包含违反非空、唯一或外键约束的值
- python - 如果最终返回值,则不会引发 python 异常
- android - Android AltBeacon 背景和前景一起
- ubuntu - 使用 youtube-dl 重命名下载的 YT 视频
- firebase - Cloud Functions:从 Cloud Storage 压缩多个文档
- docker - 使用 containerd 在 Kubernetes 中运行 docker