Open file in __init__() python

折月煮酒 提交于 2019-12-10 17:15:13

问题


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

回答1:


Since you open the file in one method and use it an 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 to 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()



回答2:


I guess you should instantiate the class and the "check" method should check one row at a time.

This works, but if your teacher has not told you about the yield statement he will know you are cheating:

class Program(object):
    def __init__(self, fname):
        self.line_checker = self.make_checker(fname)

    def make_checker(self, fname):
        with open(fname) as i:
            for line in i:
                yield len(set(line.split())) < 2

    def check(self):
        try:
            return self.line_checker.next()
        except StopIteration:
            return None


来源:https://stackoverflow.com/questions/27574146/open-file-in-init-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!