嘿我有以下问题,我需要打开一个文件__init__()
, 与check
函数我需要检查该文件的行中的字符串/数字是否相同。如果不是,它应该返回True
如果是的话它应该返回False
,如果没有更多的行None
。我不知道文件中有多少行。我的代码工作正常,测试人员给了我 90%,但它说我不关闭文件,我明白为什么它这么说,但不知道在哪里放置关闭。但是如果我用打开它with
它应该可以工作,但我不知道如何让它以这种方式工作。
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)
"""
示例文件:
15 9 22
2014 2015 2014 2015
p py pyt pyth pytho python
ab ab ab ab ab
由于您在一种方法中打开文件并在另一种方法中使用它,因此您不能使用with
类内部的声明。您可以添加一个方法来关闭文件,并让关闭成为调用者的问题。对于调用者来说,一个流行的解决方案是使用contextlib.closing
。把它们放在一起......
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)