错误的文件描述符错误 [英] Bad file descriptor error
本文介绍了错误的文件描述符错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我尝试执行以下代码:
$ $ $ $ $ $ $ $ $ $
$ fout = file('test.out','wb')
在范围内(10):
a = f.read(1)
fout.write(a )
f.close()
f = fout
f.seek(4)
print f.read(4)
其中'test'
是任意文件,我得到:
Traceback(最近一次调用的最后一个):
在< module>文件中的testbad.py
print f.read(4)
IOError:[Errno 9]错误的文件描述符
然而,如果我改变fout行来使用一个临时文件:
import tempfile
f = file('test','rb')
fout = tempfile.NamedTemporaryFile()
在范围内(10):
a = f.read(1 )
fout.write(a)
f.close()
f = fout
f.seek(4)
print f .read(4)
没有错误。有谁知道这是为什么?我希望第一个案子能够奏效,但是我一定是做错了。
在此先感谢您的帮助!
fout 来写入,而不是读取。打开这两个使用
fout = file('test.out','r + b')
If I try executing the following code
f = file('test','rb')
fout = file('test.out','wb')
for i in range(10):
a = f.read(1)
fout.write(a)
f.close()
f = fout
f.seek(4)
print f.read(4)
Where 'test'
is any arbitrary file, I get:
Traceback (most recent call last):
File "testbad.py", line 12, in <module>
print f.read(4)
IOError: [Errno 9] Bad file descriptor
If however, I change just the fout line to use a temporary file:
import tempfile
f = file('test','rb')
fout = tempfile.NamedTemporaryFile()
for i in range(10):
a = f.read(1)
fout.write(a)
f.close()
f = fout
f.seek(4)
print f.read(4)
There are no errors. Does anyone know why this is? I would have expected the first case to work, but I must be doing something wrong.
Thanks in advance for any help!
解决方案
you've only opened the file fout
for writing, not reading. To open for both use
fout = file('test.out','r+b')
这篇关于错误的文件描述符错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文