gpt4 book ai didi

python - CSV writer 打印额外的引号

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:49 25 4
gpt4 key购买 nike

我正在学习 Python 脚本。我想读取一个 TSV 文件并以如下特定格式打印结果,

输入文件[制表符分隔]:

1   john   henry   1.234 

输出:

1,
"john",
"henry",
1.234

我写了下面的代码。

tsvfile = csv.reader(open('input.tsv' , 'r'), delimiter='\t')
outfile = csv.writer(open('output.txt' , 'w+'), escapechar='\"', quoting=csv.QUOTE_NONE)

row_number = 1
for row in tsvfile:
outfile.writerow([row[0]+","])
outfile.writerow(['"'+row[1]+'"'+","])
outfile.writerow(['"'+row[2]+'"'+","])
outfile.writerow([row[3]])
row_number = row_number + 1

它生成的输出为

1,
""john""",
""henry""",
1.234

脚本打印 ", 而不是 ,"" 而不是 "。我试图理解这种行为。

谁能帮我解释为什么我的脚本到处都打印额外的 "?我应该如何生成预期的输出?

最佳答案

也许这样做,我只是读取 CSV 文件,然后遍历每一行,然后拆分它,然后用 ',\n' 加入它(不要忘记使用 repr):

with open('filname.csv','r') as f, open('outfilename.txt','w') as f2:
l=[',\n'.join(repr(x) for x in i.split()) for i in f]
f2.write('\n'.join(l))

如果不需要cotes,做:

with open('filname.csv','r') as f, open('outfilename.txt','w') as f2:
l=[',\n'.join(i.split()) for i in f]
f2.write('\n'.join(l))

关于python - CSV writer 打印额外的引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51833386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com