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'. import collections import csv with ope
Solution 1:
apparently changing the line: cr = csv.writer(f,lineterminator='\n')
into: cr = csv.writer(f,sys.stdout, lineterminator='\n')
and adding import sys
to the imports solves the problem.
Solution 2:
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.
Solution 3:
This is a simple feasible solution:
import collections
import csv
withopen('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]
withopen('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
):
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
):
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.
Solution 4:
The Python newline character is, '\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")])
Post a Comment for "How To Remove Newline Characters From Csv File"