2

I'm using a basic block to sort and print a .csv file. It is sorted and printed correctly apart from several blank lines being printed but they don't exist within the actual csv file.

file = open("class1.csv", "r")
sort = sorted(file,key=operator.itemgetter(0))
for eachline in sort:
    print (eachline)
1
  • operator.itemgetter(0) will sort by the first character of each line. Are you sure you weren't trying to sort by the first column of the CSV? Commented Apr 19, 2015 at 10:38

1 Answer 1

2

The problem is that iterating over a file leaves the newline characters on the end:

>>> for i in open("a.py"):
...     print(repr(i))
... 
'import math\n'
'\n'
'\n'
<snipped>

Therefore, when you print the lines, the print function adds another "\n" to the end, and you get something similar to:

>>> print("import math\n")
import math

>>>

The easiest way to remedy this (I am assuming you are using Python 3, judging by the brackets with the print) is to use the end option for print:

for eachline in sort:
    print(eachline, end="")

This will stop print from adding an extra "\n" (it adds "" instead, which does nothing), and so there are no extra newlines:

>>> print("import math\n", end="")
import math
>>>

If you are on python 2 or don't want to modify the print, you can strip the "\n" using str.replace:

for eachline in sort:
    print(eachline.replace("\n", ""))
Sign up to request clarification or add additional context in comments.

3 Comments

Using 'replace' worked brilliantly, thank you @matsjoyce
@Harry Could you please accept this answer then, so that other users know this problem has been solved? Thanks.
For Python 2, you can simply use print eachline, to suppress the newline the print statement normally adds. This is equivalent to a print(eachline, end="") function call in Python 3.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.