python - 如何使用 'os' 从 'with' 打开文件对象?

标签 python subprocess fdopen

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

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

>>>

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

谢谢

最佳答案

使用这个表格,它有效。

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

关于python - 如何使用 'os' 从 'with' 打开文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19557513/

相关文章:

python - 如何获取python打印功能的源代码?

python multiprocessing无法控制多个长时间运行的控制台exe?

python - 使用fabric来操作数据库连接

python - 使用 kwargs 包装一个接受可选参数结构的函数

python - 树莓派 : terminate raspistill command from python

c - 是否可以从 FILE* 中拯救文件描述符?

c++ - Q文件/文件* : How to properly close the handle?

python - pyqtgraph ImageView和彩色图像

Python - 对目录中的每个文件执行命令行函数?