如何阻止csv.writer().writerows()向数据文件中添加额外的行?

o3imoua4  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(84)

我有一个正在编写的程序,我使用csv文件来保存会话之间的数据。每当我使用saveList()保存数据时,数据都会在每个数据填充行之间保存额外的行。
这是一个问题,因为当我使用init_entryList()从文件中读取数据时,它会将这些额外的行作为列表中的值读取。然后,每一个空白行在保存后都会添加另一个空白行,每次运行程序时,间隔都会加倍。
现在我在init_entryList()中有一个变通方法,它在沿着之前删除了多余的行,但一定有更好的方法来处理这个问题。

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")

字符串
我试过将entryList用作字典而不是列表的列表,但在将所需数据从文件加载回程序中使用时遇到了一些问题。

gzszwxb4

gzszwxb41#

文档中给出了一个示例:

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'])

字符串
它指定newline=''。尝试将其添加到代码with open(saveFile, 'w', newline='') as csvfile:

相关问题