添加标题行以在Python中导出csv

2024-09-24 02:25:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python在我的最终输出csv中添加一个标题行。我该怎么做?首先,我要删除主文件items.csv的头文件,因为python在头文件的末尾也添加了'target'字。但添加单词后,我想写一个新的标题。你知道吗

这是我的密码:

import csv
from itertools import islice
import os

with open('items.csv') as sample, open('items_50.csv', "w") as out:
    csv1=csv.reader(sample)
    header = next(csv1, None)
    csv_writer = csv.writer(out)
    sirali = sorted(csv1, key=lambda x:int(x[0]), reverse=True)
    csv_writer.writerows(islice(sirali,50))


file1=open('items_50.csv','rb') 
readfile=csv.reader(file1,)
file2=open('final.csv','wb')
writefile=csv.writer(file2,delimiter='"')
result=()


for row in readfile:   
    result= [row[0]+','+row[1]+','+row[2]+','+row[3]+'target']
    writefile.writerow(result)

file1.close()
file2.close()

我的一个例子最终.csv现在:

0,apple,orange,gettarget
25,steven,jack,sendtarget
33,pencil,book,sendtarget
8,notebook,cellphone,gettarget

我想把它做成这样:

count,thing,owner,action
0,apple,orange,gettarget
25,steven,jack,sendtarget
33,pencil,book,sendtarget
8,notebook,cellphone,gettarget

谢谢你。你知道吗


Tags: csvimport标题target头文件itemsresultopen
2条回答

在此条件下循环之前

if os.path.getsize(f_path) > 0: writefile.writerow(["count", "thing", "owner", "action"])

如果文件为空,这将添加行。你知道吗

for循环之前执行:

writefile.writerow(["count", "thing", "owner", "action"])

顺便说一句:你能做到

for row in readfile:
    row[3] += 'target' 
    writefile.writerow(row)

相关问题 更多 >