Vor Vor - 6 days ago 5
Linux Question

open() doesn't open file descriptor in the for loop

I'm trying to create a for loop and open bunch of file descriptios, but unfortunately it doesn't work for me in the for loop.

In [1]: import os

In [2]: os.getpid()
Out[2]: 6992

In [3]: open('/tmp/aaa', 'w')
Out[3]: <open file '/tmp/aaa', mode 'w' at 0x7fa7c9645ae0>

In [4]: for i in xrange(10):
...: open('/tmp/aaa{0}'.format(str(i)), 'w')
...:


Above script only opens 1 fd:

vagrant@workspace:~$ ls -alht /proc/6992/fd/ | grep tmp
l-wx------ 1 vagrant vagrant 64 Nov 29 15:18 11 -> /tmp/aaa


Questions:

1 - how to open multiple file descriptors using for loop?

2 - what's wrong with above code?

Answer

open returns a file object that you operate on.

If you discard the return value, Python will garbage collect it, thus closing the file. So, calling open in a loop without using the return value is useless as all the file objects returned will be garbage collected.

What you want is to save those file objects:

Files = [open('/tmp/aaa{0}'.format(str(i)), 'w') for i in xrange(10)]
Comments