confused about the readline() return in Python

后端 未结 3 1987
-上瘾入骨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

    You need to understand the concept of file pointers. When you read the file, it is fully consumed, and the pointer is at the end of the file.

    It seems that the readline() is not working at all.

    It is working as expected. There are no lines to read.

    when I disable print a.read(), the readline() gets back to work.

    Because the pointer is at the beginning of the file, and the lines can be read

    Is there any solution that I can use read() and readline() at the same time?

    Sure. Flip the ordering of reading a few lines, then the remainder of the file, or seek the file pointer back to a position that you would like.

    Also, don't forget to close the file when you are finished reading it

提交回复
热议问题