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

Python写入CSV文件追加新行时出现位置错位问题求助

问题根因

CSV写入错位问题核心是两个常见的写入逻辑漏洞:

  • 手动编辑CSV后,Excel、记事本等工具保存文件时,不会自动在最后一行末尾补换行符,此时用追加模式写入的新内容会直接拼接在旧文件最后一行的尾部,而非另起新行,最终出现错位。
  • 使用a+模式打开文件后直接调用file.tell()判断是否为空的逻辑存在平台兼容性问题:部分操作系统下a+模式打开文件时指针默认定位在文件末尾,file.tell()永远不会返回0,会导致表头写入逻辑永久失效。

修复方案

调整文件打开和写入逻辑,先判断文件是否为空、再检查末尾是否有换行符,修正后的代码如下:

import csv
import os

def Logger(date, Sub, fear, anger, anticip, trust, surprise, sadness, disgust, joy, positivity, negativity):
    fileName = myDict[Sub]
    file_exists = os.path.exists(fileName) and os.path.getsize(fileName) > 0
    
    # 先处理末尾无换行的问题
    if file_exists:
        with open(fileName, 'r+b') as f:
            # 定位到文件末尾前2个字节(兼容Windows\r\n和Linux\n换行格式)
            f.seek(-2, os.SEEK_END)
            trailing_chars = f.read()
            # 如果末尾没有换行符,先补一个
            if b'\n' not in trailing_chars:
                f.write(b'\n')
    
    # 追加写入内容
    with open(fileName, 'a+', newline="", encoding='utf-8') as file:
        writer = csv.writer(file)
        # 用文件是否存在判断是否需要写表头,兼容性更好
        if not file_exists:
            writer.writerow(["Date", "Asset", "Fear", "Anger", "Anticipation", "Trust", "Surprise", "Sadness", "Disgust", "Joy",
                        "Positivity", "Negativity"])
        writer.writerow([date, Sub, fear, anger, anticip, trust, surprise, sadness, disgust, joy, positivity, negativity])

额外说明

  • 建议将date、Sub等变量作为参数传入Logger函数,避免依赖全局变量导致的不可控问题
  • 打开文件时指定encoding='utf-8'可以避免中文乱码问题

CSV错位示例截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 23:54:05