Open file in __init__() python
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()
![Matis](https://i.stack.imgur.com/kQJlN.jpg?s=256&g=1)
Matis
Updated on July 20, 2022Comments
-
Matis almost 2 years
Hey I have a following problem, I need to open a file in
__init__()
, and withcheck
function I need to check if strings/numbers in rows of this file are the same or not. If they aren't it should returnTrue
if they are it should returnFalse
, and if there are no more linesNone
. 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 withwith
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