Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad file descriptor error

Tags:

python

file

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!

like image 472
astrofrog Avatar asked Mar 03 '10 05:03

astrofrog


People also ask

What is meant by file descriptor?

A file descriptor is an unsigned integer used by a process to identify an open file. The number of file descriptors available to a process is limited by the /OPEN_MAX control in the sys/limits. h file. The number of file descriptors is also controlled by the ulimit -n flag.

How do I close file descriptor?

close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).


1 Answers

you've only opened the file fout for writing, not reading. To open for both use

fout = file('test.out','r+b')
like image 124
cobbal Avatar answered Oct 08 '22 22:10

cobbal