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!