"[Errno 22] Invalid argument" on close()?

This is bizarre. I have the following code:

fh=open('/mnt/1wire/3A.'+blower.id_+'/PIO.BYTE','wb')
fh.write(bytes(onOff))
fh.close()

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.