confused about the readline() return in Python

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

提交回复
热议问题