DrunkCloud DrunkCloud - 7 months ago 9
Python Question

Python open() function : can't normally print the file after using a for loop

As the title: after using a for loop to print every line of a file, I can't print the file with another for loop.

Does the for loop change the pos variable?

pos = open('nnn.txt','r')
print pos
count = 0
for line in pos:
line = line.rstrip()
if line.startswith('Hey'):
print line
count += 1
print count

count = 0
print line
for lines in pos:
lines = lines.rstrip()
print lines
count += 1
print count


the content of the file

cmd

Answer

[Does] the for loop change the pos variable?

Yes it does. Iterating over a file moves the "pointer" to the end of the file, so you can no longer read from it.

You can reset the pointer to the beginning using pos.seek(0). Then you can read from it again.