Append new row to old csv file python

You can use the code below to add a new row to an existent csv file. 

with open('document.csv','a', newline='') as csvfile:
    fieldnames = ['fold', 'accuracy','precision', 'recall', 'f1']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writerow({'fold': kfold, 'accuracy': accuracy, 'precision': precision, 'recall': recall, 'f1' : f1})
                

1.Opening a file with the "a" parameter allows you to append to the end of the file instead of simply overwriting the existing content. 

2.newline="", you can distinguish the difference between with and without newline="" from the below example (I found it online).

[input]

with open('./data/competitions-from-python.csv', 'w', newline='') as f:
    data_writer = csv.writer(f, delimiter=',')
    data_writer.writerow(['Year', 'Event', 'Winner']) # First Line acts as header
    data_writer.writerow(['1995', 'Best Kept Lawn', 'None'])
    data_writer.writerow(['1999', 'Gobstones', 'Welch National'])
    data_writer.writerow(['2006', 'World Cup', 'Burkina Faso'])
Now let’s view it:

[input]

with open("./data/competitions-from-python.csv") as f:
    csv_file = csv.reader(f) 
    comp = []
    for line in csv_file: 
        print(line)
        comp = comp + line 
[output]

['Year', 'Event', 'Winner']
['1995', 'Best Kept Lawn', 'None']
['1999', 'Gobstones', 'Welch National']
['2006', 'World Cup', 'Burkina Faso']
Everything seems as it should. Now, lets append this file, but this time, we will not use the newline=''

[input]

with open('./data/competitions-from-python.csv', 'a') as f:
    data_writer = csv.writer(f, delimiter=',')
    data_writer.writerow(['2011', 'Butter Cup', 'France'])
    data_writer.writerow(['2013', 'Coffee Cup', 'Brazil'])
    data_writer.writerow(['2006', 'Food Cup', 'Italy'])
Now, lets read the file again:

[input]

with open("./data/competitions-from-python.csv") as f:
    csv_file = csv.reader(f) 
    comp = []
    for line in csv_file: 
        print(line) 
        comp = comp + line
[output]

['Year', 'Event', 'Winner']
['1995', 'Best Kept Lawn', 'None']
['1999', 'Gobstones', 'Welch National']
['2006', 'World Cup', 'Burkina Faso']
['2011', 'Butter Cup', 'France']
[]
['2013', 'Coffee Cup', 'Brazil']
[]
['2006', 'Food Cup', 'Italy']
[]

You can find further details here!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值