1

I'm trying to do a script which reads a line (URL) in a text file, checks its code_status and then print to the user, however, when using for loop it gives wrong code_status while testing with one URL in the request.get(url) gives the right one.

Problematic code

import requests
with open('test2.txt', 'r+') as arquivo:
        for linhas in arquivo:
                url = requests.get(linhas)
                print url.status_code

Achieves the right code.

import requests         
url = requests.get(URL)
print url.status_code

You guys can test both the txt file and single URL with the following URL: https://api.github.com/user

What am I doing wrong?

5
  • github url is wrong, can you fix it please? Commented Sep 5, 2015 at 16:53
  • 2
    Possibly the text file has a newline character at the end and the URL is thus wrong. Commented Sep 5, 2015 at 16:53
  • @KamyarGhasemlou There's nothing wrong with url o.O. Commented Sep 5, 2015 at 16:56
  • @PauloAlmeida I've noticed that when the urls are printed in the terminal but the text file are well orderly Commented Sep 5, 2015 at 16:56
  • 1
    @Milbol when you read from file lin-by-line, you end up with a new line at the end of each entry, you ahve to strip it. see my answer for the fix. Commented Sep 5, 2015 at 16:58

1 Answer 1

2

Most probably your problem is because of the \n character at the end of each line. this should fix it:

import requests
with open('test2.txt', 'r+') as arquivo:
        for linhas in arquivo:
                url = requests.get(linhas.strip())
                print url.status_code
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.