0

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

1 Answer 1

1
import random
import csv

def generatebookid():
    book_id = []
    count =0
    while (count<5):

        book_id.append(random.randint(1000,9999))

        count+=1
    return book_id

def savecsv():

    booklist = []
    for _ in range(5):
        booklist.append(generatebookid())

    csvfile =r"path\to\my\directory\sometext.csv"

    with open (csvfile, "a") as output:
        fieldnames = ['Book ID']
        writer = csv.writer(output, delimiter =',', lineterminator ="\n")

        writer.writerows([fieldnames])
        for books in booklist:
            writer.writerows([books])

generatebookid()
savecsv()

So your generatebookid program was just setting the book_id once to a random int. In order to get the behaviour you want from booklist.append() you need some kind of loop which will call the generatebookid multiple times. Alternatively (and what I did) was generate a list of book ids and then return that to booklist. This will write as you expect as a whole line of 5 IDs.

P.S they aren't overwriting, it's in append mode

Edit: Changed it to write 5 different lists of book ids to the file. Added the for _ in range(5) to denote number of file entries and iterated through these with for books in booklist.

Sign up to request clarification or add additional context in comments.

1 Comment

@JoanT no worries, glad I could help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.