首页 > 解决方案 > 从文本文件中检查 URL 文件是否存在

问题描述

我正在尝试做以下事情:

1 - open a text file containing a list with URLs (http://example.com). <br>
2 - read the text file and check if the path existe. <br>
3 - write the results back in another text file.

我尝试了以下代码:

    import urllib2
    file = open('file.txt', 'r')

    search = urllib2.urlopen(file + "/js/tools.js")

    if search.code == 200:
        print "Exists!"

我感谢提供的任何帮助。

标签: pythonpython-3.xpython-2.7urllib2

解决方案


考虑到您有文件Filename,因为链接是逐行存储的

import requests
with open(filename,'r') as file, open(filename2,'w+') as file2:
    for url in file.readlines():
        check = requests.get(url)
        if check.ok:
            file2.write(url)

推荐阅读