confused about the readline() return in Python

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-27 02:19

    When you open a file you get a pointer to some place of the file (by default: the begining). Now whenever you run .read() or .readline() this pointer moves:

    1. .read() reads until the end of the file and moves the pointer to the end (thus further calls to any reading gives nothing)
    2. .readline() reads until newline is seen and sets the pointer after it
    3. .read(X) reads X bytes and sets the pointer at CURRENT_LOCATION + X (or the end)

    If you wish you can manually move that pointer by issuing a.seek(X) call where X is a place in file (seen as an array of bytes). For example this should give you the desired output:

    print a.read()
    a.seek(0)
    print a.readline()
    print a.readline()
    print a.readline()
    
    0 讨论(0)
提交回复
热议问题