Python - 打开连续文件而不是实际打开每个文件

Viv*_*osh -1 python python-3.x

如果我要阅读Python 3.2中的许多文件,比如30-40,我想将文件引用保留在列表中

(所有文件都在一个公共文件夹中)

无论如何我可以打开所有文件到列表中各自的文件句柄,而不必通过file.open()函数单独打开每个文件

Hen*_*ter 6

这很简单,只需根据文件路径列表使用列表推导.或者,如果您只需要一次访问它们,请使用生成器表达式以避免一次打开所有四十个文件.

list_of_filenames = ['/foo/bar', '/baz', '/tmp/foo']
open_files = [open(f) for f in list_of_filenames]
Run Code Online (Sandbox Code Playgroud)

如果要在某个目录中的所有文件上使用句柄,请使用以下os.listdir函数:

import os
open_files = [open(f) for f in os.listdir(some_path)]
Run Code Online (Sandbox Code Playgroud)

我认为一个简单的,平坦的目录在这里,但注意到os.listdir返回的路径列表的所有文件对象在指定目录下,无论是"真正"的文件或目录.因此,如果您打开的目录中有目录,则需要使用os.path.isfile以下内容过滤结果:

import os
open_files = [open(f) for f in os.listdir(some_path) if os.path.isfile(f)]
Run Code Online (Sandbox Code Playgroud)

Also, os.listdir only returns the bare filename, rather than the whole path, so if the current working directory is not some_path, you'll want to make absolute paths using os.path.join.

import os
open_files = [open(os.path.join(some_path, f)) for f in os.listdir(some_path) 
              if os.path.isfile(f)]
Run Code Online (Sandbox Code Playgroud)

With a generator expression:

import os
all_files = (open(f) for f in os.listdir(some_path)) # note () instead of []
for f in all_files:
    pass # do something with the open file here.
Run Code Online (Sandbox Code Playgroud)

In all cases, make sure you close the files when you're done with them. If you can upgrade to Python 3.3 or higher, I recommend you use an ExitStack for one more level of convenience .