If I type this in Python:
open("file","r").read()
sometimes it returns the exact content of the file as a string, some other times it returns an empty string (even if the file is not empty). Can someone explain what does this depend on?
If I type this in Python:
open("file","r").read()
sometimes it returns the exact content of the file as a string, some other times it returns an empty string (even if the file is not empty). Can someone explain what does this depend on?
When you reach the end of file (EOF) , the
.read
method returns''
, as there is no more data to read.Doc links:
read()
tell()
seek()
From the
file.read()
method documentation:You have hit the end of the file object, there is no more data to read. Files maintain a 'current position', a pointer into the file data, that starts at 0 and is incremented as you read dada.
See the
file.tell()
method to read out that position, and thefile.seek()
method to change it.There is another issue, and that is that the file itself might be leaked and only reclaimed late or even never by the garbage collector. Therefore, use a with-statement:
This is hard to digest for anyone with a C-ish background (C, C++, Java, C# and probably others) because the indention there always creates a new scope and any variables declared in that scope is inaccessible to the outside. In Python this is simply not the case, but you have to get used to this style first...