Search code examples
pythoncsvimportsave

How do I stop csv.writer().writerows() from adding extra rows to my data file?


I have a program I am writing, and I am using a csv file to save the data between sessions. Whenever I save the data using saveList() the data is saved with extra rows in-between each data filled row.

This is a problem, because when I read the data from the file using init_entryList() it reads those extra rows as values in the list. Then each blank row gets another blank row added after saving, and the gaps double every time the program is run.

For now I have a workaround in init_entryList() that cuts out the extra rows before passing it along, but there must be a better way of handling this.


import csv

def init_entryList():
#read data from saveFile, then return it as a list of lists
    #open file and extract data
    with open(saveFile, 'r') as read_obj:
        csv_reader = csv.reader(read_obj)
        fileData = list(csv_reader) # convert string to list
    #remove the uneeded blank rows
    while (fileData.count([])):
        fileData.remove([])
    #return the cleaned up data
    return fileData
    
def addEntry():
#takes data, then appends it to the entryList. Used for prototyping rn
    acct = input("Enter acct #: ")
    date = input("Enter date: ")
    name = input("Enter name: ")
    tech = input("Enter tech: ")
    moneyOwed = input("Enter past due balance: ")
    service = input("Enter Service type: ")
    followUps = 0
    notes = input("Enter Notes: ")
    
    entryData = [date,acct,name,tech,moneyOwed,service,followUps,notes]

    entryList.append(entryData)
    
def saveList():
#save the entryList to permanent file
    print('Saving Data...')
    with open(saveFile, 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerows(entryList)        #entryList is a list of lists, the data for my program. 

###DEBUGGING
entryList = init_entryList() #comment out to disable initialization. 
addEntry() #to test if new data is being saved properly, add new data
saveList() #save data from session

print("Program done")

I've tried using entryList as a dictionary instead of a list of lists, but I had several issues with getting it to load the data I needed from the file back into the program to be used.


Solution

  • There is an example given in the documentation:

    import csv
    with open('eggs.csv', 'w', newline='') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=' ',
                                quotechar='|', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
        spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
    

    It specifies newline=''. Try adding that to your code with open(saveFile, 'w', newline='') as csvfile: