Open file in __init__() python

19,147

Since you open the file in one method and use it in another, you can't use the with statement internal to the class. You can add a method to close the file and let the closing be the caller's problem. A popular solution for the caller is to use contextlib.closing. Putting it all together...

class Program:
    def __init__(self, file_name):
        self.t = open(file_name, 'r')

    def check(self):
        ...

    def close(self):
        if self.t:
            self.t.close()
            self.t = None


import contextlib
with contextlib.closing(Program('myfile.txt')) as program:
    program.check()
Share:
19,147
Matis
Author by

Matis

Updated on July 20, 2022

Comments

  • Matis
    Matis almost 2 years

    Hey I have a following problem, I need to open a file in __init__(), and with check function I need to check if strings/numbers in rows of this file are the same or not. If they aren't it should return True if they are it should return False, and if there are no more lines None. I do not know how many lines are there going to be in the file. My code is working kind of, tester is giving me 90%, but it says I do not close the file, I understand why it is saying, but do not know where to put the close. However if I opened it with with it should be working but I do not know how to get it working that way.

    My Code:

    class Program:
        def __init__(self, file_name):
            self.t = open(file_name, 'r')
    
        def check(self):
            row = self.t.readline()
    
            array = []
    
            for i in row.split():
                if i not in array:
                    array.append(i)
    
            if row.split() == []:
                return None
            elif array == row.split():
                return True
            else:
                return False
    
    """
    #testing
    
    if __name__ == '__main__':
        u = Program('file.txt')
        z = True
        while z is not None:
            z = u.check()
            print(z)
    
    """
    

    Example file:

    15 9 22
    2014 2015 2014 2015
    p py pyt pyth pytho python
    ab ab ab ab ab