How to close all the opened files using Python?

PythonServer Side ProgrammingProgramming

There is no way in python natively to track all opened files. To do that you should either track all the files yourself or always use the with statement to open files which automatically closes the file as it goes out of scope or encounters an error.

For example

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

You can also create a class to enclose all files and create a single close function to close all the files.

For example

class OpenFiles():
    def __init__(self):
        self.files = []
    def open(self, file_name):
        f = open(file_name)
        return f
    def close(self):
        list(map(lambda f: f.close(), self.files))
files = OpenFiles()
# use open method
foo ="text.txt", "r")
# close all files
Published on 26-Dec-2017 11:36:16