1

Trying to figure out why these unexpected newlines are being printed in a simple script. All I want to do in this script is read in a file, and print the contents of each line.

The code is like this:

#!/usr/bin/python
import sys

# This script should just iterate over a file and echo the contents of each line

f=open(sys.argv[1],'r')
for line in f:
  line.rstrip('\n')
  print "Line 1 is: " + line
f.close()

The input file is just 2 lines:

#cat users 
root
dontexist
#

When I run the script with this input file, there are extra newlines in the output:

#./test.py users
Line 1 is: root

Line 1 is: dontexist

#

What am I missing? Thanks all.

Kevin
  • 13
  • 2

2 Answers2

2

rstrip and similar functions (e.g. replace, strip, etc.) return a copy with the changed string as opposed to changing the string in place. You want to do line = line.rstrip("\n")

Foon
  • 6,148
  • 11
  • 40
  • 42
1

You need to do :

line = line.rstrip('\n')

Currently you don't make change to the variable "line"

Alfie
  • 2,706
  • 1
  • 14
  • 28