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

Python生成CSV文件时单词间出现多余逗号的问题排查求助

问题排查:生成文件中字符被拆分添加多余逗号

问题背景

运行Python代码后控制台输出符合预期,但生成的new.csv文件中每个字符间被自动添加了多余逗号,完全偏离期望格式。相关信息如下:

输入文件(usergroups.csv)内容

idNo;UserGroup;Name;Description;Owner;Visibility;Members
id;grp1;bhalaji;asdfgh;bhalaji;public
abc
def
ghi
id;grp2;bhalaji;asdfgh;bhalaji;private
abc
def
ghi

原代码

import csv
output = []
temp = []
currIdLine = ""
with( open ('usergroups.csv', 'r')) as f:
    for lines in f.readlines():
        line = lines.strip()
        if not line:
            print("Skipping empty line")
            continue
        if line.startswith('idNo'): # append the header to the output
            output.append(line)
            continue
        if line.startswith('id'):
            if temp:
                print(temp)
                output.append(currIdLine + ";" + ','.join(temp))
                temp.clear()
            currIdLine = line
        else:
            temp.append(line)
output.append(currIdLine + ";" + ','.join(temp))
print("\n".join(output))
with open('new.csv', 'w') as f1:
    writer = csv.writer(f1)
    writer.writerows(output)

当前错误输出(new.csv)

u,u,i,d,;,U,s,e,r,G,r,o,u,p,;,N,a,m,e,;,D,e,s,c,r,i,p,t,i,o,n,;,O,w,n,e,r,;,V,i,s,i,b,i,l,i,t,y,;,M,e,m,b,e,r,s
i,d,:;,g,r,p,1,;,b,h,a,l,a,j,i,;,a,s,d,f,g,h,;,b,h,a,l,a,j,i,;,p,u,b,l,i,c,;,a,b,c,,d,e,f,,g,h,i
i,d,:;,g,r,p,2,;,b,h,a,l,a,j,i,;,a,s,d,f,g,h,;,b,h,a,l,a,j,i,;,p,r,i,v,a,t,e,;,a,b,c,,d,e,f,,g,h,i

期望输出

uuid;UserGroup;Name;Description;Owner;Visibility;Members
id:grp1;bhalaji;asdfgh;bhalaji;public;abc,def,ghi
id:grp2;bhalaji;asdfgh;bhalaji;private;abc,def,ghi

问题原因

  1. 核心问题:使用csv.writer.writerows()时,传入的output是字符串列表。writerows()会将每个字符串视为可迭代对象,逐个拆分字符后用默认分隔符(逗号)拼接写入,导致每个字符间出现逗号。
  2. 额外问题:原代码未处理id;grp1到id:grp1的格式转换,也未将表头idNo替换为uuid。

修正后的代码

output = []
temp = []
currIdLine = ""
with open('usergroups.csv', 'r') as f:
    for lines in f.readlines():
        line = lines.strip()
        if not line:
            print("Skipping empty line")
            continue
        if line.startswith('idNo'):
            # 替换表头为期望格式
            output.append("uuid;UserGroup;Name;Description;Owner;Visibility;Members")
            continue
        if line.startswith('id'):
            if temp:
                print(temp)
                # 处理id行的分号转冒号
                formatted_id_line = currIdLine.replace('id;', 'id:')
                output.append(formatted_id_line + ";" + ','.join(temp))
                temp.clear()
            currIdLine = line
        else:
            temp.append(line)
# 处理最后一组数据
formatted_id_line = currIdLine.replace('id;', 'id:')
output.append(formatted_id_line + ";" + ','.join(temp))

# 直接写入文件,保持和控制台输出一致
print("\n".join(output))
with open('new.csv', 'w') as f1:
    f1.write('\n'.join(output))

关键改动说明

  • 移除csv模块,直接使用文件写入方法,避免csv.writer的自动拆分逻辑
  • 替换表头的idNo为uuid
  • 将id;grpX转换为id:grpX
  • 使用f1.write('\n'.join(output))写入,确保文件内容和控制台输出完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:35:51