I am getting the subject error on the close. If I comment out the close, the error goes away although I’m not sure the data is actually written without the close. Since the error makes no sense to me, I’m hoping someone here can shed some light on it. TIA.
Is this on some device like the Raspberry Pi? From the filename, it looks like this is a special – writing to it will control some device, rather than just store data on disk.
Files in Python are normally buffered (what you write is temporarily stored in memory, so it can be sent in larger chunks, which is more effective). See the buffering argument to open.
You can call the flush method before closing the file to write the data immediately.
Closing the file will also flush the buffer, so you’ll get the error produced by writing the data. The error you get depends on whatever device driver you’re controlling through the file.
If you don’t call close(), the data should get written eventually, but any error will be silenced. Since you generally want to know when something goes wrong, I’d recommend using the with statement with files – that way, the file is always properly closed when you’re done with it.
Thanks for the reply. Indeed, it is a Pi and I am using 1-wire file system (owfs). Interestingly, I added ‘fh.flush()’ to the code and now the error occurs on that statement. It seems to me that if something were wrong with the file handle the error would have occurred on the write. In any case I changed the code to use ‘with’ which did not help. At least now I get the error on ‘fh.write’. I guess I need to try/except to get more detail about the error.
Using try/except does not produce any additional detail. However, I have a test script that does the same thing and it works. Try as I may, I can find no difference between the two. The conclusion has to be that there is something else outside the open and write that is causing the problem. I have no clue how to debug this.
No, 22 is usually EINVAL, meaning an argument is invalid. Like the
subject line suggested.
Since the POSIX close returns EBADF (9) for an unknown (not open) file
descriptor I would expect it is getting an out of range value, eg a
negative number.
OTOH, it is possible that some other system call is getting an invalid
value, since Python’s close sits above some library code before getting
down to an OS call (where errno values come from). More context needed.
As mentioned above, you’re opening in buffered mode, so you don’t see the error until the buffer is flushed to the OS file, which is when the actual write() system call occurs. In Linux, if a write fails with EINVAL, generally it means the device/file isn’t suitable for writing. See man -s2 write.