如何从CSV文件中删除换行符 [英] How to remove newline characters from csv file
本文介绍了如何从CSV文件中删除换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下面的代码部分,可从csv文件 prom output.csv中读取值。并将它们写成一个新的 sorted output.csv。
I have the below part of code that reads values from the csv file "prom output.csv" and writes them sorted in a new one "sorted output.csv".
import collections
import csv
with open("prom output.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr)
for r in cr:
d[r[0]].append(r[1])
with open("sorted output.csv","w") as f:
cr = csv.writer(f,delimiter=",")
cr.writerow(header)
od = collections.OrderedDict(sorted(d.items()))
for k,v in od.items(): s
cr.writerow([k,",".join(v)])
但是,输出(见下文)在每行和我想删除它们。有人可以帮忙吗?
However the output (see below) has spaces between each line and i would like to remove them. Can anybody help?
输入文件 prom output.csv每行之间没有空格,如下所示
The input file "prom output.csv" has no spaces between each line as seen below
就像我的输出看起来像这样:
as a last midification i would like my output to look like:
有什么建议吗?
推荐答案
更改
cr = csv.writer(f,delimiter=",")
至
cr = csv.writer(f,delimiter=",", lineterminator='\n')
可以解决问题。
我试过 cr = csv.writer(f,lineterminator ='\n')
仍然有效。
does the trick.
I tried cr = csv.writer(f, lineterminator='\n')
and it still works.
这篇关于如何从CSV文件中删除换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文