To elaborate on Rohith's answer, they way you are opening the file is important.
The with
works by internally calling seleral functions, so I tried it out step by step:
>>> fd = os.open("c:\\temp\\xyxy", os.O_CREAT)
>>> f = os.fdopen(fd, 'w')
>>> myfile = f.__enter__()
>>> myfile.write("213")
>>> f.__exit__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 9] Bad file descriptor
What? Why? And why now?
If I do the same with
>>> fd = os.open(filepath, os.O_CREAT | os.O_RDWR)
all works fine.
With write()
you only wrote to the file object's output puffer, and f.__exit__()
essentiall calls f.close()
, which in turn calls f.flush()
, which flushes this output buffer to disk - or, at least, tries to do so.
But it fails, as the file is not writable. So a [Errno 9] Bad file descriptor
occurs.