如何使用with从“os”打开file对象?

2024-10-01 13:37:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用'操作系统打开()'如下

>>> 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

>>>

你知道我怎么打开文件对象吗os.fdopen操作系统使用“with”以便自动关闭连接?在

谢谢


Tags: csvtexthelloosaswithopenmyfile
2条回答

要详细说明Rohith's answer,打开文件的方式很重要。在

with通过内部调用seleral函数来工作,因此我一步一步地尝试:

>>> 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

什么?为什么?为什么现在?在

如果我也这么做

^{pr2}$

一切正常。在

使用write()只写了file对象的输出puffer,f.__exit__()essentiall调用f.close(),后者反过来调用{},后者将输出缓冲区刷新到磁盘上,或者至少尝试这样做。在

但它失败了,因为文件不可写。因此发生[Errno 9] Bad file descriptor。在

用这个表格,它起作用了。在

with os.fdopen(os.open(filepath,os.O_CREAT | os.O_RDWR ),'w') as fd:  
    fd.write("abcd")

相关问题 更多 >