You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows系统下Python写入CSV出现空行问题求助(Mac无此问题)

解决Windows下Python写入CSV出现空行的问题

嗨,这个问题我之前帮朋友排查过,本质是Windows和Mac的换行符处理逻辑不同,再加上你打开文件的方式没适配csv模块的要求导致的。

问题根源

  • Windows系统默认用\r\n作为换行符,而现代Mac用\n
  • 当你直接用open('quotes.csv', 'a')打开文件时,Windows的Python会自动把输出的\n转换成\r\n;但csv模块本身已经会在每行末尾写入\r\n来兼容跨平台,这样就会变成\r\r\n——用Excel或者普通文本编辑器打开时,就会显示成空行。而Mac上不会做这个自动转换,所以一切正常。

修复方案

核心就是打开文件时指定newline='',让csv模块自己处理换行符,同时优化一下你的代码结构(比如把open放到with语句里,更安全规范):

import csv
import os

fieldnames = ['quote', 'author']
quoteNum = int(input("How many quotes do you want to enter: "))

# 关键:打开文件时添加newline='',让csv模块管理换行
with open('quotes.csv', 'a', newline='') as myFile:
    fileEmpty = os.stat('quotes.csv').st_size == 0
    writer = csv.DictWriter(myFile, fieldnames=fieldnames)
    if fileEmpty:
        writer.writeheader()
    for entry in range(1, quoteNum + 1):
        # 修正了拼写错误authur→author
        author_name = input("Enter the Author's name: ")
        # 用f-string让输入提示更简洁
        quoteValue = input(f"Enter the Quote by {author_name} here: ")
        writer.writerow({'author': author_name, 'quote': quoteValue})

额外说明

  • newline=''是Python csv模块官方推荐的写法,它会告诉Python不要自动转换换行符,完全交给csv模块处理,这样生成的CSV文件在Windows和Mac上都会正常显示,不会出现空行。
  • 顺便帮你修正了代码里的小拼写错误(比如authur_name、qoutes),让代码更易读~

内容的提问来源于stack exchange,提问作者Slim buzz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:06:32