如何使用“with"从“os"打开文件对象? [英] How to open file object from 'os' using 'with'?

查看:45
本文介绍了如何使用“with"从“os"打开文件对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用os.open()"打开文件,如下所示

<预><代码>>>>文件路径'C:\\Shashidhar\\text.csv'>>>fd = os.open(filePath,os.O_CREAT)>>>使用 os.fdopen(fd, 'w') 作为我的文件:... myfile.write("你好")IOError: [Errno 9] 错误的文件描述符>>>

知道如何使用with"从 os.fdopen 打开文件对象,以便自动关闭连接?

谢谢

解决方案

使用这个表单,它奏效了.

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

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

解决方案

use this form, it worked.

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

这篇关于如何使用“with"从“os"打开文件对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆