如何阻止csv.writer().writerows()向CSV文件添加多余空行?
CSV保存时出现多余空行的解决方案
问题根源
在Windows系统中,使用csv.writer写入文件时,若采用默认的open('file.csv', 'w')模式,系统会自动将换行符\n转换为\r\n。而csv.writer默认的行结束符就是\r\n,这会导致最终每行末尾多出一个\r,表现为文件中的空行。每次读取再保存时,空行被当作有效行写入,进而导致空行数量翻倍。
最优解决方案:指定newline=''打开文件
修改saveList()函数中的文件打开逻辑,添加newline=''参数,让csv模块自行处理换行符,彻底避免系统自动转换带来的空行问题:
def saveList(): #save the entryList to permanent file print('Saving Data...') with open(saveFile, 'w', newline='') as csvfile: # 添加newline=''参数 writer = csv.writer(csvfile) writer.writerows(entryList)
这是Python官方csv模块文档推荐的标准做法,从根源上解决空行问题,无需再在读取阶段额外清理。
优化读取阶段的空行清理(兼容旧数据)
如果已有文件中存在空行,或需要兼容历史数据,可以将init_entryList()中的空行清理逻辑替换为更高效的列表推导式,替代循环remove的低效率写法:
def init_entryList(): #read data from saveFile, then return it as a list of lists with open(saveFile, 'r', newline='') as read_obj: # 读取时也建议添加newline='' csv_reader = csv.reader(read_obj) # 过滤空行,同时排除全为空白字符的行(按需选择) fileData = [row for row in csv_reader if row and any(cell.strip() for cell in row)] return fileData
关于字典格式的处理
若想改用字典存储数据,可使用csv.DictReader和csv.DictWriter来实现,示例如下:
写入字典数据
def saveList_as_dict(): print('Saving Data as Dict...') # 定义字段名,需与字典的key一一对应 fieldnames = ['date', 'acct', 'name', 'tech', 'moneyOwed', 'service', 'followUps', 'notes'] with open(saveFile, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() # 写入表头行 writer.writerows(entryList) # entryList为字典组成的列表
读取字典数据
def init_entryList_as_dict(): fieldnames = ['date', 'acct', 'name', 'tech', 'moneyOwed', 'service', 'followUps', 'notes'] with open(saveFile, 'r', newline='') as read_obj: csv_reader = csv.DictReader(read_obj, fieldnames=fieldnames) next(csv_reader) # 跳过表头行(如果写入时包含表头) # 过滤空行 fileData = [row for row in csv_reader if any(row[field].strip() for field in fieldnames)] return fileData
这样就能顺畅地用字典格式存储和加载数据,解决之前遇到的转换问题。
内容的提问来源于stack exchange,提问作者Nifty_Biscuit
相关产品推荐
相关产品推荐

