如何在python中定义文件对象列表

use*_*329 -1 python arrays object python-2.7

为了定义指向文件的单个文件对象,在python中我们只写:

f = open ('file_name.txt','wb')
Run Code Online (Sandbox Code Playgroud)

我想知道几个(比方说50个)文件的情况,我怎么能创建一个50个文件对象的数组(或python术语列表),每个文件对象指向一个名称相同的索引的文本文件?

Sup*_*Man 5

Python中的列表只是引用的集合,它们可以引用您想要的任何内容,包括文件对象.

files = [
           open("file1.txt",'wb')
           open("file2.txt",'wb')
           open("file3.txt",'wb')
           ...
        ]
Run Code Online (Sandbox Code Playgroud)

根据您想要收集的方式,您可以使用发电机.例如

files = [open("file_{}".format(x),'wb') for x in range(12)]
Run Code Online (Sandbox Code Playgroud)

或者,如果您想从文件夹中获取所有文件:

files = [open(file, 'wb') for file in os.listdir(yourFolder)]
Run Code Online (Sandbox Code Playgroud)

打开太多要小心,因为这可能会成为记忆问题.

  • 比用完可用文件描述符更少的内存问题. (2认同)