简体   繁体   English

如何从csv文件中删除换行符

[英]How to remove newline characters from csv file

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".我有下面的代码部分,它从 csv 文件“prom output.csv”中读取值并将它们写入一个新的“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?有人可以帮忙吗?

在此处输入图片说明

The input file "prom output.csv" has no spaces between each line as seen below输入文件“prom output.csv”每行之间没有空格,如下所示

在此处输入图片说明

as a last midification i would like my output to look like:作为最后的中间化,我希望我的输出看起来像:

在此处输入图片说明

any suggestions?有什么建议吗?

显然将行: cr = csv.writer(f,lineterminator='\\n') cr = csv.writer(f,sys.stdout, lineterminator='\\n')为: cr = csv.writer(f,sys.stdout, lineterminator='\\n')并将import sys添加到导入中解决了问题。

Changing改变

cr = csv.writer(f,delimiter=",")

to

cr = csv.writer(f,delimiter=",", lineterminator='\n')

does the trick.诀窍。

I tried cr = csv.writer(f, lineterminator='\\n') and it still works.我试过cr = csv.writer(f, lineterminator='\\n')并且它仍然有效。

This is a simple feasible solution:这是一个简单可行的解决方案:

import collections
import csv

with open('prom output.csv') as f:
    header = next(csv.reader(f))
    d = collections.OrderedDict()
    for r in csv.reader(f):
        try:
            d[r[0]] += ','+r[1]
        except:
            d[r[0]] = ','+r[1]

with open('sorted output.csv', 'w') as f:
    cw = csv.writer(f)
    cw.writerow(header)
    for k, v in d.items():
        f.write(k+v+'\n')

For the input of the following CSV file ( prom output.csv ):对于以下 CSV 文件 ( prom output.csv ) 的输入:

case,event,startTime,completeTime
101,A
101,B
101,Y
102,C
102,D
102,U
103,A
103,B
103,Y

The output was ( sorted output.csv ):输出是( sorted output.csv ):

case,event,startTime,completeTime
101,A,B,Y
102,C,D,U
103,A,B,Y

Which is the output as you intended it to be.这是您想要的输出。

The Python newline character is, '\\n'. Python 换行符是“\\n”。 Therefore to remove the newline character (and hence the blank lines that are being printed) from your string, try:因此,要从字符串中删除换行符(以及正在打印的空行),请尝试:

cr.writerow([k, (",".join(v)), .strip("\n")])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM