2013-10-24 47 views
1

我尝试使用“os.open()”文件,如下如何使用'with'从'os'打开文件对象?

>>> 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使用“与”,这样的连接可以automatially关闭?

谢谢

+3

你为什么要用这种方式打开一个文件,而不是用标准的'open()'或者甚至是'io.open()'来打开文件? – monkut

+0

我在这之前设置了os.nice(19)。我想利用操作系统来创建和打开文件,这样我就可以在执行这些操作时拥有“完美”的功能! – Shashi

+0

@Shashi。我不明白。 'os.nice'与'os.open'有什么关系? – glglgl

回答

1

使用这种形式,它的工作。

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

为了详细说明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 

什么?为什么?为什么呢?

如果我做同样的

>>> fd = os.open(filepath, os.O_CREAT | os.O_RDWR) 

一切工作正常。

随着write()你只写文件对象的输出河豚,并f.__exit__() essentiall调用f.close(),进而调用f.flush(),其中刷新此输出中buffer to disk - 或者,至少,试图这样做。

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

相关问题