I'm trying to open file using 'os.open()' as below
>>> filePath
'C:\\Shashidhar\\text.csv'
>>> fd = os.open(filePath,os.O_CREAT)
>>> with os.fdopen(fd, 'w') as myfile:
... myfile.write("hello")
IOError: [Errno 9] Bad file descriptor
>>>
Any idea how can I open the file object from os.fdopen using "with" so that connection can be closed automatially?
Thanks
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:What? Why? And why now?
If I do the same with
all works fine.
With
write()
you only wrote to the file object's output puffer, andf.__exit__()
essentiall callsf.close()
, which in turn callsf.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.use this form, it worked.