如何从列表中打开文件

时间:2013-08-29 18:24:58

标签: python file list

我想出了如何浏览目录并查找某种类型的文件并将其添加到列表中。现在我有一个包含文件名称的列表。我如何打开所有这些?以下是我到目前为止的情况:

import os
import glob
import subprocess

os.chdir("/Users/blah/Desktop/Data")
reflist = glob.glob('*raw_ref.SDAT')
actlist = glob.glob('*raw_act.SDAT')

for i in reflist:
    os.popen("%r" %i)

for j in actlist:
    os.popen("%r" %j)

P.S。我在Mac上

3 个答案:

答案 0 :(得分:4)

ref_files = map(open, reflist)

或者,如果您希望更好地控制open()的参数:

ref_files = [open(filename, ...) for filename in reflist]

答案 1 :(得分:4)

我建议尽可能少地同时打开文件。

for file in reflist:
    with open(file) as f:
        pass # do stuff with f
    # when with block ends, f is closed

for file in actlist:
    with open(file) as f:
        pass # do stuff with f
    # when with block ends, f is closed

如果您出于某种原因需要同时打开所有文件(我觉得不太可能),那么请使用NPE的解决方案。

请记住,当您不使用文件I / O的上下文管理器(如此处使用with)时,您需要在完成后手动关闭文件。

答案 2 :(得分:0)

@Brian说对了#34;我建议尽可能少地同时打开文件。"但这取决于你想做什么。如果您需要多个打开的文件进行阅读,可以尝试这样做以确保文件最后关闭:

# I don't know MAC path names.
filenames = ['/path/to/file', 'next/file', 'and/so/on']
# here the file descriptors are stored:
fds = []
try:
    for fn in filenames:
        # optional: forgive open errors and process the accessible files
        #try:
            fds.append(open(fn))
        #except IOError:
        #    pass

    # here you can read from files and do stuff, e.g. compare lines
    current_lines = [fd.readline() for fd in fds]
    # more code

finally:
    for fd in fds:
        fd.close()