python文件中的init_在__init __()python中打开文件

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

解决方案

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值