compare lines in a file with a string

If you create the following file xx.in:

test line 1
test line 2

and run the following Python program, you’ll see exactly why the match is failing:

file = open('xx.in')
for line in file:
    print '[%s]' % (line)

The output is:

[test line 1
]
[test line 2
]

showing that the newline characters are being left on the line when they’re read in. If you want them stripped off, you can use:

line = line.rstrip('\n')

This will remove all newline characters from the end of the string and, unlike strip(), will not affect any other whitespace characters at either the start or end.

Leave a Comment