问题
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
回答1:
use this form, it worked.
with os.fdopen(os.open(filepath,os.O_CREAT | os.O_RDWR ),'w') as fd:
fd.write("abcd")
回答2:
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.
来源:https://stackoverflow.com/questions/19557513/how-to-open-file-object-from-os-using-with