使用太多的公开电话。如何关闭所有文件?

时间:2015-06-11 07:18:10

标签: python io

我正在尝试更改很多pdf文件。因此,我必须打开很多文件。我多次使用这种方法。所以python提供错误 太多打开的文件

我希望我的代码是grace.writer很多相似

readerbanner = PyPDF2.pdf.PdfFileReader(open('transafe.pdf', 'rb'))
readertestpages = PyPDF2.pdf.PdfFileReader(open(os.path.join(Cache_path, cache_file_name), 'rb'))
writeroutput.write(open(os.path.join(Output_path,cache_file_name), 'wb'))

or

writer_output.write(open(os.path.join(Cache_path, str(NumPage) + "_" + pdf_file_name), 'wb'))
reader_page_x = PyPDF2.pdf.PdfFileReader(open(os.path.join(PDF_path, pdf_file_name), 'rb'))

所有打开的方法都不使用 f_name = open(“path”,“r”)

因为所有打开的文件都有句号。我知道这个位置,但不知道所有打开的文件有多接近。

4 个答案:

答案 0 :(得分:3)

要关闭文件,只需在其上调用close()

您还可以使用上下文管理器来处理文件关闭:

with open('file.txt') as myfile:
    # do something with myfile here

# here myfile is automatically closed

答案 1 :(得分:2)

据我所知,此代码不应该打开太多文件。除非它运行了很多次。

无论如何,问题在于你打电话:

PyPDF2.pdf.PdfFileReader(open('transafe.pdf', 'rb'))

和类似的。这将创建一个文件对象,但不保存对它的引用。 您需要为所有公开呼叫做什么:

file = open('transafe.pdf', 'rb')
PyPDF2.pdf.PdfFileReader(file)

然后:

file.close()

当你不再使用该文件时。 如果要同时关闭多个文件,请将它们放在列表中。

答案 2 :(得分:1)

with statement

with open("abc.txt", "r") as file1, open("123.txt", "r") as file2:
    # use files
    foo = file1.readlines()

# they are closed automatically
print(file1.closed)
# -> True
print(file2.closed)
# -> True

包装函数

files = []
def my_open(*args):
    f = open(*args)
    files.append(f)
    return f

# use my_open
foo = my_open("text.txt", "r")

# close all files
list(map(lambda f: f.close(), files))

包装类

class OpenFiles():
    def __init__(self):
        self.files = []

    def open(self, *args):
        f = open(*args)
        self.files.append(f)
        return f

    def close(self):
        list(map(lambda f: f.close(), self.files))


files = OpenFiles()

# use open method
foo = files.open("text.txt", "r")

# close all files
files.close()

答案 3 :(得分:0)

ExitStack可能有用: https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception