Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9192117
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T20:50:49+00:00 2026-06-17T20:50:49+00:00

I’m trying to create a script which makes requests to random urls from a

  • 0

I’m trying to create a script which makes requests to random urls from a txt file e.g.:

import urllib2

with open('urls.txt') as urls:
    for url in urls:
        try:
            r = urllib2.urlopen(url)
        except urllib2.URLError as e:
            r = e
        if r.code in (200, 401):
            print '[{}]: '.format(url), "Up!"

But I want that when some url indicates 404 not found, the line containing the URL is erased from the file. There is one unique URL per line, so basically the goal is to erase every URL (and its corresponding line) that returns 404 not found.
How can I accomplish this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T20:50:50+00:00Added an answer on June 17, 2026 at 8:50 pm

    The easiest way is to read all the lines, loop over the saved lines and try to open them, and then when you are done, if any URLs failed you rewrite the file.

    The way to rewrite the file is to write a new file, and then when the new file is successfully written and closed, then you use os.rename() to change the name of the new file to the name of the old file, overwriting the old file. This is the safe way to do it; you never overwrite the good file until you know you have the new file correctly written.

    I think the simplest way to do this is just to create a list where you collect the good URLs, plus have a count of failed URLs. If the count is not zero, you need to rewrite the text file. Or, you can collect the bad URLs in another list. I did that in this example code. (I haven’t tested this code but I think it should work.)

    import os
    import urllib2
    
    input_file = "urls.txt"
    debug = True
    
    good_urls = []
    bad_urls = []
    
    bad, good = range(2)
    
    def track(url, good_flag, code):
        if good_flag == good:
            good_str = "good"
        elif good_flag == bad:
            good_str = "bad"
        else:
            good_str = "ERROR! (" + repr(good) + ")"
        if debug:
            print("DEBUG: %s: '%s' code %s" % (good_str, url, repr(code)))
        if good_flag == good:
            good_urls.append(url)
        else:
            bad_urls.append(url)
    
    with open(input_file) as f:
        for line in f:
            url = line.strip()
            try:
                r = urllib2.urlopen(url)
                if r.code in (200, 401):
                    print '[{0}]: '.format(url), "Up!"
                if r.code == 404:
                    # URL is bad if it is missing (code 404)
                    track(url, bad, r.code)
                else:
                    # any code other than 404, assume URL is good
                    track(url, good, r.code)
            except urllib2.URLError as e:
                track(url, bad, "exception!")
    
    # if any URLs were bad, rewrite the input file to remove them.
    if bad_urls:
        # simple way to get a filename for temp file: append ".tmp" to filename
        temp_file = input_file + ".tmp"
        with open(temp_file, "w") as f:
            for url in good_urls:
                f.write(url + '\n')
        # if we reach this point, temp file is good.  Remove old input file
        os.remove(input_file)  # only needed for Windows
        os.rename(temp_file, input_file)  # replace original input file with temp file
    

    EDIT: In comments, @abarnert suggests that there might be a problem with using os.rename() on Windows (at least I think that is what he/she means). If os.rename() doesn’t work, you should be able to use shutil.move() instead.

    EDIT: Rewrite code to handle errors.

    EDIT: Rewrite to add verbose messages as URLs are tracked. This should help with debugging. Also, I actually tested this version and it works for me.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
Basically, what I'm trying to create is a page of div tags, each has
I am trying to understand how to use SyndicationItem to display feed which is
I am trying to render a haml file in a javascript response like so:
I have an autohotkey script which looks up a word in a bilingual dictionary
I'm trying to select an H1 element which is the second-child in its group
I have a text area in my form which accepts all possible characters from
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to create an if statement in PHP that prevents a single post

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.