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

时间:2015-05-21 16:18:14

标签: python arrays python-2.7 object

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

f = open ('file_name.txt','wb')

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

4 个答案:

答案 0 :(得分:5)

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

files = [
           open("file1.txt",'wb')
           open("file2.txt",'wb')
           open("file3.txt",'wb')
           ...
        ]

根据您想要收集它们的方式,您可以使用生成器。例如

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

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

files = [open(file, 'wb') for file in os.listdir(yourFolder)]

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

答案 1 :(得分:4)

除了Guilaumes的答案,您还可以使用列表理解(文档here),如下所示:

myFiles = [ open('file'+str(i)+'.txt', 'wb') for i in range(3) ]

myFiles[0].write('hello world'

答案 2 :(得分:1)

以下是创建文件列表的方法:

myfiles=[]
for i in range(3):
    f = open ('file'+str(i),'wb')
    myfiles.append(f)

myfiles[0].write("hello world")

答案 3 :(得分:0)

文件就像Python中的其他所有对象一样。因此,您可以将字符串放入带有

的列表lst
lst[n] = "value"

lst.append(value)

因此,当您了解open()函数返回文件对象时,您可以将文件放入带有

的列表中
lst[n] = open(filename, 'wb')

lst.append(open(filename, 'wb')

因此,要创建一个打开文件列表,您只需在计算文件名的循环中使用最后一个示例(尽管如果您已经拥有文件名,您可以轻松地遍历文件名列表)。

file_list = []
for i in range(50):
    filename = "file{}.txt".format(i)
    file_list.append(open(filename, 'wb'))

使用列表推导可以在单个表达式中更紧凑地(但也更不透明地)实现这一点。口味不同。

file_list = [open("file{}.txt".format(i), 'wb') for i in range(50)]

虽然打开50个文件不太可能在现代操作系统上造成问题,但您应该知道操作系统可以要求的资源有上限。