confused about the readline() return in Python

后端 未结 3 1983
-上瘾入骨i
-上瘾入骨i 2021-01-27 01:54

I am a beginner in python. However, I have some problems when I try to use the readline() method.

f=raw_input(\"filename> \")
a=open(f)
print a.read()
print a         


        
3条回答
  •  后悔当初
    2021-01-27 01:57

    The file object a remembers it's position in the file.

    • a.read() reads from the current position to end of the file (moving the position to the end of the file)
    • a.readline() reads from the current position to the end of the line (moving the position to the next line)
    • a.seek(n) moves to position n in the file (without returning anything)
    • a.tell() returns the position in the file.

    So try putting the calls to readline first. You'll notice that now the read call won't return the whole file, just the remaining lines (maybe none), depending on how many times you called readline. And play around with seek and tell to confirm whats going on.

    Details here.

提交回复
热议问题