3

I find each time I read a line, the end of of line character is included as well (showing as '$' in vi set list command) and am wondering how to automatically remove it when reading from a file?

From the print output, you can see end of line is output each time so that it seems two lines are printed each time.

Here is the code and input file, with output,

import sys

fileInput = open(sys.argv[1], 'r')

for line in fileInput:
        print line

python TestLineParse.py TestInput.txt.csv
216

218

219

248

head TestInput.txt.csv
216
218
219
248
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lin Ma
  • 9,739
  • 32
  • 105
  • 175

2 Answers2

7

Try using the rstrip function to remove the newline character:

import sys

fileInput=open(sys.argv[1],'r')

for line in fileInput:
    print line.rstrip('\n')
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
3

Try using this:

print line.rstrip()
Undo
  • 25,519
  • 37
  • 106
  • 129
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485