IF 语句表现相反
IF statement behaving the opposite way
我写了一个小脚本来扫描以下格式的文本文件。
然后输出带有重定向 URL 的不同文本文件,前提是存在重定向。否则,我想打印出 "No redirection"。但出于某种原因,恰恰相反。
下面是我的代码,你能解释一下我做错了什么吗?
import urllib.request
inc_input = input("Please enter the file name\n")
file_name = open(inc_input)
f = open('output.txt', 'w')
for line in file_name:
eachurl = line.strip()
redirected = urllib.request.urlopen(eachurl)
finalurl = redirected.geturl()
if eachurl == finalurl:
f.write(eachurl + "\t" + finalurl + "\n")
else:
f.write(eachurl + "\t" + "No redirection" + "\n")
f.close()
if eachurl != finalurl: #when the urls are not same, it's a redirection
f.write(eachurl + "\t" + finalurl + "\n")
else:
f.write(eachurl + "\t" + "No redirection" + "\n")
您的逻辑似乎与您的预期相反,我添加了注释以澄清:
if eachurl == finalurl:
# no redirection happened since we're in the original url (==)
f.write(eachurl + "\t" + finalurl + "\n")
else:
# redirection happened, different url
f.write(eachurl + "\t" + "No redirection" + "\n")
使用not
反转条件或反转物体。目前该消息具有误导性。
我写了一个小脚本来扫描以下格式的文本文件。
然后输出带有重定向 URL 的不同文本文件,前提是存在重定向。否则,我想打印出 "No redirection"。但出于某种原因,恰恰相反。
下面是我的代码,你能解释一下我做错了什么吗?
import urllib.request
inc_input = input("Please enter the file name\n")
file_name = open(inc_input)
f = open('output.txt', 'w')
for line in file_name:
eachurl = line.strip()
redirected = urllib.request.urlopen(eachurl)
finalurl = redirected.geturl()
if eachurl == finalurl:
f.write(eachurl + "\t" + finalurl + "\n")
else:
f.write(eachurl + "\t" + "No redirection" + "\n")
f.close()
if eachurl != finalurl: #when the urls are not same, it's a redirection
f.write(eachurl + "\t" + finalurl + "\n")
else:
f.write(eachurl + "\t" + "No redirection" + "\n")
您的逻辑似乎与您的预期相反,我添加了注释以澄清:
if eachurl == finalurl:
# no redirection happened since we're in the original url (==)
f.write(eachurl + "\t" + finalurl + "\n")
else:
# redirection happened, different url
f.write(eachurl + "\t" + "No redirection" + "\n")
使用not
反转条件或反转物体。目前该消息具有误导性。