使用嵌套 ifs,在应该评估内部"else"时会跳过它,我错过了什么?



我想检查"check.txt"文件是否存在;如果存在,则执行另一个if语句,检查其内容是否与预期结果匹配,如果不执行else。另一方面,如果外部 if 被评估为假,则应评估外部其他。我的问题是,当内部if被评估为假时,外部else被评估而不是内部else!它被跳过了!

我使用了以下代码:

def checht():
if os.path.isfile("check.txt"):
# creation_time = os.path.getctime("check.txt")
# if (time.time() - creation_time) // (24 * 3600) <= 7:
hold = os.path.isfile("check.txt")
print(hold)
f = open("check.txt", "r")
print(f.readline())
if f.readline() == sp2.find('span', class_="thetime date updated").get_text().strip():
f.close()
print("inner if")
return "nothing is new"
else:
f.close()
os.remove("check.txt")
sys.exit()
# create_file_and_status_update()
else:
print("in outer else")
create_file_and_status_update() 

刚刚测试过,似乎您没有文件"check.txt",所以总是要去外面

您的设置似乎有问题。如果你运行这样的东西,它的行为就像你期望的那样,"outter false"永远不会被评估

if True:
print('outter true')
if not True:
print('inner true')
else:
print('inner false')
else:
print('outter false')

外出真

内部错误

之后什么都不会执行

return "nothing is new"  

代码行。因为程序脱离了整个功能。你也不应该使用

sys.exit

在代码的这一点上。

编辑: 请像这样更改您的代码并向我们提供打印结果。

def checht():
if os.path.isfile("check.txt"):
# creation_time = os.path.getctime("check.txt")
# if (time.time() - creation_time) // (24 * 3600) <= 7:
hold = os.path.isfile("check.txt")
print(hold)
f = open("check.txt", "r")
firstLine= f.readline()
searchfor = sp2.find('span', class_="thetime date updated").get_text().strip()
print(firstLine)
print(searchfor)       
print(f.readline())
if firstLine == searchfor:
f.close()
print("inner if")
return "nothing is new"
else:
f.close()
os.remove("check.txt")
sys.exit()
# create_file_and_status_update()
else:
print("in outer else")
create_file_and_status_update()

因为现在,我不知道是什么

sp2.find('span', class_="thetime date updated").get_text().strip()

等于在您发布的上下文中。

相关内容

最新更新