IF语句表现相反

时间:2017-01-25 10:24:31

标签: python python-3.x urllib

我写了一个小脚本,用以下格式扫描文本文件。

enter image description here

然后仅在存在重定向时输出带有重定向URL的不同文本文件。否则,我想打印出#34;没有重定向"。但出于某种原因,恰恰相反。

以下是我的代码,您能否解释一下我做错了什么?

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()

2 个答案:

答案 0 :(得分:2)

您的逻辑似乎与您的期望相反,我已添加评论以澄清:

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来反转条件或反转实体。目前该消息具有误导性。

答案 1 :(得分:1)

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")