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
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
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.
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:
.read()
reads until the end of the file and moves the pointer to the end (thus further calls to any reading gives nothing).readline()
reads until newline is seen and sets the pointer after it.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()