Reputation: 192
I'm trying to do File IO, and I wrote a program to:
The text I'm trying to read is stored in a file called input.txt. Here is the exact text...
I am a file.
This is a line.
This is the last line.
and here is my function to read that file and print out my desired results.
in1 = open("input.txt", 'r')
x=0
for line in in1:
print ('Line %d ' % (x)),
print ("(%d chars): " % (len(line))),
print (line),
x += 1
My terminal output should be
Line 0 (12 chars): I am a file.
Line 1 (15 chars): This is a line.
Line 2 (22 chars): This is the last line.
But my actual terminal output is
Line 0 (13 chars): I am a file.
Line 1 (16 chars): This is a line.
Line 2 (22 chars): This is the last line.
When my function is counting the length of the line, I believe it is counting the Enter Key I press in order to move to the next line as an extra character. How do I fix this?
Upvotes: 0
Views: 347
Reputation: 20336
That's because each line has a new-line character at the end that you don't see. Use len(line.rstrip())
instead.
Upvotes: 5