Im currently trying to store the book id values into a CSV file through python. The book id is generated randomly with 4 digits for 5 times using a while loop starting from 1000 to 9999. What I wanted to do is to save all of the book ids into the CSV file. However, only the latest values are saved into the CSV file and the previous book id values were overwritten. I would appreciate it if any help was given.
These are my codes.
import random
import csv
def generatebookid():
global book_id
count =0
while (count<5):
book_id = random.randint(1000,9999)
print (book_id)
count+=1
def savecsv():
booklist = []
booklist.append(book_id)
csvfile ='C:\\Users\\dell\\Desktop\\MPbookid.csv'
with open (csvfile, "a") as output:
fieldnames = ['Book ID']
writer = csv.writer(output, delimiter =',', lineterminator ="\n")
writer.writerows([fieldnames])
writer.writerows([booklist])
generatebookid()
savecsv()
This is the output I got from opening the CSV file in excel. Im supposed to get 5 values but only the latest book id value is saved. csv