Reputation: 39
I have a list of values that I am trying to append to a csv file every time my program runs but my code only appends once and never again. What am I doing wrong here.
import random
import csv
import numpy as np
from csv import writer
randomlist = []
for i in range (0,5):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)
np.savetxt("test.csv",
randomlist,
fmt ='% s')
def append_list_as_row(file_name, list_of_elem):
with open(file_name, 'a+', newline='') as file:
csv_writer = writer(file)
csv_writer.writerow(list_of_elem)
append_list_as_row('test.csv',randomlist)
Upvotes: 0
Views: 127
Reputation: 85
The problem is you're saving a new "test.csv"
file everytime you run the code with the function np.savetxt
.
Try separating this part of the code:
np.savetxt("test.csv",
randomlist,
fmt ='% s')
from the rest of the code, let it run only once
Upvotes: 1
Reputation: 303
When you call np.savetxt("test.csv", randomlist, fmt ='% s')
, this method overrides test.csv
, so just don't call it, you can do something like:
from csv import writer
import numpy as np
import random
import csv
def main():
randomlist = []
for i in range (0,5):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)
# np.savetxt("test.csv", randomlist, fmt ='% s')
append_list_as_row('test.csv', randomlist)
def append_list_as_row(file_name, list_of_elem):
with open(file_name, 'a+', newline='') as file:
csv_writer = writer(file)
csv_writer.writerow(list_of_elem)
if __name__ == '__main__':
main()
Upvotes: 2