我正在尝试使用open()在python中逐行读取文件。下面是一个可以工作的小代码片段(Snippet- 1),但是当将相同的工作逻辑放入类和__init__()函数中时,相同的函数停止工作,不生成输出,也不生成错误消息,只是使用退出代码0完成执行。
您能帮助识别Snippet-2的问题吗?我假设__init__()不喜欢调用open()。提前谢谢。
#Snippet -1
f = open("file.txt", 'r')
for line in f:
print(line)#Snippet -2
class InitProcess:
def __init__(self):
self.count = 0
filepath = "file.txt"
try:
self.fd = open(filepath)
for line in self.fd:
print(line)
finally:
self.fd.close()发布于 2021-08-12 16:05:03
__init__()中的代码在创建类实例(即类的对象)时执行。尝试创建类的对象,如下所示:
test_process = InitProcess()只要这一行被执行,你的代码就会被执行。
https://stackoverflow.com/questions/68760707
复制相似问题