[Tutor] new to python

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jul 25 03:43:46 EDT 2017

On 25/07/17 04:58, N6Ghost wrote:

> this code works

> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
> for line in f:
>      for line in f:
>          #print(line.rstrip())
>          print(line)
> f.close()

> the out put skips the first line of the inputfile and puts a blank line 
> inbetween

I'm not sure why you have two for loops? Why did you do that?
Can you explain your thinking there?

Remove one of the for... lines.

Your code does this:

> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')

open the file and assign it to 'f'

> for line in f:

get the first line from f and assign it to 'line'

>      for line in f: print(line)

get the next line from f and assign it to 'line'
This overwrites the value from the first for loop above.
The line is then printed.

The second loop then repeats for all of the remaining
lines in the file. At the end of the second for loop
control returns to the top for loop. But, since the file
is now empty, the top loop never gets any more values
from f, so it terminates.

The blank lines are caused by the fact that the lines
in the file end in a newline character and print() adds
a newline of its own. Either reinstate your rstrip()
call or stop print() adding a newline with

print(line, end='')

I'm also not sure why you posted two copies of
your code? I assume you only use one since otherwise
you would have told us that you got two lots of output?

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list