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

修改CSV行数据后出现多余换行的原因及解决办法

解决CSV写入后出现多余换行的问题

问题原因

你遇到的多余换行问题,是因为Python的csv模块写入逻辑和文件默认换行处理机制冲突了。当用open()打开文件时未指定newline='',Python会自动转换换行符为系统默认格式,而csv.writer本身也会输出换行符,两者叠加就导致每行之间多出空行。

修复方法

只需修改代码中写入文件的部分,给open()函数添加newline=''参数:

writer = csv.writer(open('doctors.csv', 'w', newline=''))
writer.writerows(lines)

额外优化点(可选)

你的代码还有几个可以调整的细节:

  • 开头的file.close少了括号,应该写成file.close(),否则文件无法正确关闭
  • 重复打开文件的逻辑可以合并,减少资源占用

优化后的完整示例代码:

import csv

# 显示所有行供选择修改
with open("doctors.csv", "r") as file:
    for idx, row in enumerate(file.readlines()):
        print(idx, row.strip())

rowchange = int(input("Enter the row number to change: "))
makechange = input("What is the new first name: ")

# 修改并写入文件
with open("doctors.csv", "r") as doctorcsv:
    lines = list(csv.reader(doctorcsv))
    lines[rowchange][1] = makechange

with open("doctors.csv", "w", newline='') as doctorcsv:
    writer = csv.writer(doctorcsv)
    writer.writerows(lines)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:01:36