Python - read file using win32file.ReadFile
A similar question:
However, in this question I did not answer. When i call
result, data = win32file.ReadFile(my_file, 4096, None)
the result is always 0, which according to the documentation means success:
The result is a tuple of (hr, string/PyOVERLAPPEDReadBuffer), where hr may be 0, ERROR_MORE_DATA or ERROR_IO_PENDING.
Even if I set the buffer to 10 and the file is much larger, the result is 0 and the data is a string containing the first 10 characters.
result, buf = win32file.ReadFile(self._handle, 10, None) while result == winerror.ERROR_MORE_DATA: result, data = win32file.ReadFile(self._handle, 2048, None) buf += data print "Hi" return result, buf
"Hello" is never printed even if the file clearly contains more data. The problem I have is how can I make sure I am reading the entire file without using a ridiculously large buffer?
source to share
As noted, if
is 0, it means success. This is exactly the opposite of the win32 api documentation which says 0 means an error has occurred.
To determine how many bytes have been read, you need to check the length of the returned string. If the size is the same size as the buffer size, then there may be more data. If it is smaller, the entire file has been read:
def readLines(self): bufSize = 4096 win32file.SetFilePointer(self._handle, 0, win32file.FILE_BEGIN) result, data = win32file.ReadFile(self._handle, bufSize, None) buf = data while len(data) == bufSize: result, data = win32file.ReadFile(self._handle, bufSize, None) buf += data return buf.split('\r\n')
You need to add error handling eg. check the result if it actually equals 0 and if not take appropriate action.
source to share