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

Python生成CSV异常:行中途换行且source字段含多余引号求助

问题根源

  1. 换行符引发CSV格式异常:从followerFile.txt读取的sourceName包含末尾换行符(\n),CSV写入器遇到含换行符的字段时,会自动用引号包裹并保留换行,导致你看到的中途换行和多余引号。
  2. 冗余且易出错的文件读取逻辑:updateCSV中同时用readlines()和linecache.getline()读取文件,不仅重复操作,还可能导致循环终止条件判断失效,同时存在重复关闭文件的问题。
  3. 不必要的手动文件关闭:rowUpdate中使用with语句打开文件时,with块结束后会自动关闭文件,无需手动调用csvFile.close()。

修复方案

1. 清理sourceName的换行符

读取关注者名称时,用strip()去除首尾空白字符(包括换行符、空格等),避免干扰CSV格式。

2. 重构updateCSV的读取逻辑

放弃linecache,直接遍历文件内容,简化代码并避免错误:

def updateCSV(accountName, targetFollowers, targetFollowing):
    # 用with语句自动管理文件生命周期
    with open('followerFile.txt','r', encoding="utf-8") as followerFile:
        for sourceName in followerFile:
            cleaned_source = sourceName.strip()
            # 跳过空行
            if cleaned_source:
                rowUpdate(accountName, cleaned_source, targetFollowers, targetFollowing)

3. 移除rowUpdate中多余的手动关闭操作

def rowUpdate(accountName, sourceName, targetFollowers, targetFollowing):
    rowData = [accountName, sourceName, 'directed', targetFollowers, targetFollowing]
    # with语句会自动关闭文件,无需手动调用close()
    with open('edges.csv','a', encoding="utf-8") as csvFile:
        csvWriter = csv.writer(csvFile)
        csvWriter.writerow(rowData)

4. 优化setupCSV的文件操作(可选)

同样用with语句简化代码,避免忘记关闭文件的问题:

def setupCSV():
    with open('edges.csv','w',encoding="utf-8") as csvFile:
        csvWriter = csv.writer(csvFile)
        csvWriter.writerow(['target','source','type','source_followers','source_following'])

修改后效果

生成的CSV将恢复正常格式,source字段不会被引号包裹,也不会中途换行:

target,source,type,source_followers,source_following
central_insurance_companies,carolpaul60,directed,1382,1265
central_insurance_companies,haif_250,directed,1382,1265
central_insurance_companies,hmadvisors,directed,1382,1265
central_insurance_companies,speakmanweaver,directed,1382,1265

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:20:34