简体   繁体   English

open()不会在for循环中打开文件描述符

[英]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. 我正在尝试创建一个for循环并打开一堆文件描述文件,但是不幸的是,在for循环中它不适用于我。

>>> import os

>>> os.getpid()
6992

>>> open('/tmp/aaa', 'w')
<open file '/tmp/aaa', mode 'w' at 0x7fa7c9645ae0>

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

Above script only opens 1 fd: 上面的脚本仅打开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? 1-如何使用for循环打开多个文件描述符?

2 - what's wrong with above code? 2-上面的代码有什么问题?

open returns a file object that you operate on. open返回您要操作的文件对象。

If you discard the return value, Python will garbage collect it, thus closing the file. 如果您放弃返回值,Python将对其进行垃圾回收,从而关闭文件。 So, calling open in a loop without using the return value is useless as all the file objects returned will be garbage collected. 因此, 不使用返回值而在循环中调用open是没有用的,因为所有返回的文件对象都将被垃圾回收。

What you want is to save those file objects: 您要保存的文件对象是:

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

Some tips: 一些技巧:

  1. str(i) isn't needed when you use format as the latter cares about type conversions itself. 使用format时不需要str(i)因为后者关心类型转换本身。
  2. You don't need the zero in {0} in the format string as well because Python inserts format s i -th argument (count starts after the format string) instead of the i -th pair of braces in the format string. 您也不需要格式字符串中的{0}中的零,因为Python会插入format s第i -th个参数(计数从格式字符串之后开始),而不是格式字符串中的第i个括号。

All in all, the code could be simplified to: 总而言之,代码可以简化为:

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

You need to get the file descriptor, and after you do whatever you want to do with it, close it to have it flushed. 您需要获取文件描述符,并在对其执行任何操作后将其关闭以将其刷新。

so you need something more like this: 所以你需要更多类似这样的东西:

for i in range(10):
    f = open('/tmp/aaa{0}'.format(str(i)), 'w')
    # manipulate the file
    f.close()

If you need to save those file descriptors to access them later in the code, you should save them somewhere, like a list. 如果需要保存这些文件描述符以在以后的代码中访问它们,则应将它们保存在某个位置,例如列表。

fs = [open('/tmp/aaa{0}'.format(str(i)), 'w') for i in range(10)]
# manipulate files
_ = [f.close() for f in fs]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM