在__init __()python中打开文件 [英] Open file in __init__() python
问题描述
嘿,我遇到以下问题,我需要在__init__()
中打开一个文件,并使用check
函数来检查此文件行中的字符串/数字是否相同.如果不是,则应返回True
;如果不是,则应返回False
;如果没有更多行,则应返回None
.我不知道文件中将有多少行.我的代码工作正常,测试人员给了我90%的费用,但是它说我不关闭文件,我理解为什么要说,但是不知道放在哪里.但是,如果我使用with
打开它,它应该可以工作,但是我不知道如何使它那样工作.
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.
我的代码:
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)
"""
示例文件:
15 9 22
2014 2015 2014 2015
p py pyt pyth pytho python
ab ab ab ab ab
推荐答案
由于使用一种方法打开文件,然后使用另一种方法,因此无法使用该类内部的with
语句.您可以添加一种方法来关闭文件,并让关闭成为调用者的问题.呼叫者常用的解决方案是使用contextlib.closing
.全部放在一起...
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()
这篇关于在__init __()python中打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!