How to remove newline characters from csv file
<p>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".</p>

<pre><code>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)]) 
</code></pre>

<p>However the output (see below) has spaces between each line and i would like to remove them. Can anybody help?</p>

<p><a href="http://i.stack.imgur.com/y6RSD.png" rel="nofollow"><img src="http://i.stack.imgur.com/y6RSD.png" alt="enter image description here"></a></p>

<p>The input file "prom output.csv" has no spaces between each line as seen below</p>

<p><a href="http://i.stack.imgur.com/SpOER.png" rel="nofollow"><img src="http://i.stack.imgur.com/SpOER.png" alt="enter image description here"></a></p>

<p>as a last midification i would like my output to look like: </p>

<p><a href="http://i.stack.imgur.com/o0igJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/o0igJ.png" alt="enter image description here"></a></p>

<p>any suggestions?</p>

<p>This is a simple feasible solution:</p>

<pre><code>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')
</code></pre>

<p>For the input of the following CSV file (<code>prom output.csv</code>):</p>

<pre>
case,event,startTime,completeTime
101,A
101,B
101,Y
102,C
102,D
102,U
103,A
103,B
103,Y
</pre>

<p>The output was (<code>sorted output.csv</code>):</p>

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

</pre>

<p>Which is the output as you intended it to be.</p>

python excel csv