How to open file object from 'os' using 'with'?

一曲冷凌霜 提交于 2019-12-24 10:57:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!