[Tutor] new to python

N6Ghost n6ghost at gmail.com
Wed Jul 26 16:53:07 EDT 2017



On 7/25/2017 12:43 AM, Alan Gauld via Tutor wrote:
> 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?
>
> HTH

final working code for this method:
# open meth 1
f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
for line in f:
         #print(line.rstrip())
         print(line.strip())
         j = line
         #print ("****below new var used****")
         #print (j)

f.close()


thanks for the replys, not sure why i had the second for loop. removing 
that remove some of the oddball behavioral issues.

next going to look into using the with....




More information about the Tutor mailing list