2016-12-14 114 views
0

嘿傢伙,所以我想從文件中讀取URL並打印,如果URL存在/可達或不可以?我不知道爲什麼這個代碼不工作: (我在讀從一個.txt文件的URL)從Python中的文件中讀取URL?

我得到的錯誤是:

name 'in_file' is not defined 

代碼:

from urllib.request import urlopen 

def is_reachable(url): 
    if urlopen(url): 
     return True 
    else: 
     return False 

in_file_name = input("Enter file name: ") 
try: 
    in_file = open(in_file_name, "r") 
except: 
    print("Cannot open " + in_file) 

line = in_file.readline().replace(" ", "") 
print(line) 

counter = 0 
while line != "": 
    if is_reachable(line) == True: 
    counter += 1 
    print("The URL on line ", counter, "is unreachable!") 
    line = in_file.readline() 
+0

什麼錯誤? –

+0

NameError:name'in_file'未定義 – Kris

+1

'line = in_file.readline()'僅在is_reachable返回'True'時調用,因爲縮進。爲什麼不用'with open()作爲in_file:for infile中的行:'block? –

回答

1

在打印不可達之前應該有其他的東西。或未檢查以打印無法訪問的網址。 現在,即使網址可以訪問,您正在打印它無法訪問。

counter = 0 
while line != "": 
    counter += 1 
    if not is_reachable(line): 
     print("The URL on line ", counter, "is unreachable!") 
    line = in_file.readline() 

還有其他一些問題與您的程序: 1.如果文件不是可讀的仍然是你的程序將繼續 2.您使用計數器變量,並明確地維護它。您可以輕鬆地使用枚舉

一個更好的辦法是:

from urllib.request import urlopen 
import sys 

def is_reachable(url): 
    try: 
     urlopen(url) 
     return True 
    except: 
     return False 

in_file_name = input("Enter file name: ") 
lines = [] 
try: 
    with open(in_file_name, 'r') as f: 
     lines = f.read().splitlines() 
except: 
    print("Cannot open " + in_file_name) 
    sys.exit(1) 

for counter, line in enumerate(lines): 
    if is_reachable(line): 
     print("The URL on line ", counter, "is reachable!") 
    else: 
     print("The URL on line ", counter, "is unreachable!") 
+0

由於他們使用'counter'來顯示行號,他們需要在所有情況下增加行數。也許'如果is_reachable(行)不是真的:'然後打印錯誤,並在讀下一行時增加計數器? –

+0

@SimonFraser感謝您指出了這一點。 –

+0

@VikashSingh我試過你的代碼,但我不知道爲什麼它不能打開文件 – Kris

0

如果無法打開文件,則應該退出腳本。由於您的代碼當前已編寫,因此如果文件無法打開,則會打印一個異常,然後嘗試運行代碼的其餘部分。

一個快速修復:

in_file_name = input("Enter file name: ") 
try: 
    in_file = open(in_file_name, "r") 
except: 
    print("Cannot open " + in_file) 
    sys.exit(1) ### you will need to import the sys module 

而且,你的輸出是錯誤的。如果urlopen返回True,那麼你應該打印它可以REACHABLE,這就是說它是UNREACHABLE。

最後,在is_reachable,你需要處理一個可能的異常,如果有一個與你試圖打開一個URL解析問題:

def is_reachable(url): 
    try: 
     urlopen(url): 
     return True 
    except urllib.error.URLError: 
     return False 
+0

這是假的,但我正在試驗,謝謝你告訴我。我會試試 – Kris

+0

有道理。實際上,我認爲你可能遇到的最大問題是最後一個問題,那就是你需要嘗試/除非調用urlopen,否則該函數會引發異常,而不僅僅是返回False,如果URL不可訪問出於任何原因。 – rumdrums

0

你在你的代碼有錯誤:

except: 
    print('yadaya ' + in_file_name) # you have used in_file 

我沒有測試這個,但應該工作:

from urllib2 import urlopen # urllib is deprecated 

if urlopen('http://google.com').getcode() >= 200 and urlopen('http://google.com') < 400: 
    print ('Yes the URL exists and works.') 

你將不得不付出更多的˚F或重定向之後。