1

I made a CSV file that contains a book, its author, and the year it released. My problem is that when the data is displayed in the file its displayed every other line. enter image description here

How can I make it where there aren't gaps between the data entries

my code:

import csv

amount = int(input("How many records would you like to add: "))
count = 0

with open("Books.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["", "Book", "Author", "Year released"])

while count < amount:

    book = input("Enter a book: ")
    author = input("Enter it's Author: ")
    year = input("Enter the year it released: ")

    headers = [count, book, author, year]
    with open("Books.csv", 'a') as f:
        writer = csv.writer(f)
        writer.writerow(headers)

    count += 1
thepunitsingh
  • 713
  • 1
  • 12
  • 30
sdew42
  • 11
  • 2

2 Answers2

0

You always need to supply newline="" on opening the file. You do so when opening to write the header, but not for the data:

with open("Books.csv", 'a') as f:    # missing newline = ''

From csv.writer

csv.writer(csvfile, dialect='excel', **fmtparams)
Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method. If csvfile is a file object, it should be opened with newline=''

  • I wouldn't open the file all the time, just keep it opened.
  • I also would opt for a for-loop to remove the need of increasing count yourself
  • lastly when converting user input to integrs, use a try-except to avoid crashing your program on bad inputs

Code:

import csv

# someone could input -42 here - or garbage
while True:
    try:
        amount = int(input("How many records would you like to add: "))
        if amount >= 0:
            break
    except ValueError:
        pass  

with open("Books.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["", "Book", "Author", "Year released"])

    for nr in range(count):
    
        book = input("Enter a book: ")
        author = input("Enter it's Author: ")
        year = input("Enter the year it released: ")
    
        data = [nr + 1, book, author, year]
        writer.writerow(data)
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

instead of with open("Books.csv", 'a') as f: use with open("Books.csv", 'a', newline='') as f:

Please refer this post for more deetails.

thepunitsingh
  • 713
  • 1
  • 12
  • 30