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!
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.
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).
you've only opened the file fout
for writing, not reading. To open for both use
fout = file('test.out','r+b')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With