0

I have a script that access an url and retrieve data like this:

 usock = urllib2.urlopen('http://www.google.com.br')
#Reads the page
    data = usock.read()
    usock.close()
#Search for links
    links = re.findall('"((http)s?://.*?)"', data)

And I would like to use a txt file as source for urls, I already have a txt file with urls by line like this:

http://www.google.com.br/
http://www.recrutamento.com.br/

I was trying to use this file with this code, but I always get IOError: [Errno 2] No such file or directory:

here is where I get stuck:

os.chdir("C:\Python27")
urls = open(os.path.join(os.getcwd(), 'ord.txt'), 'r').readlines()
for url in urls:
    usock = urllib2.urlopen(url)
#Reads the page
    data = usock.read()
    usock.close()

It displays exactly the correct path and file name:

IOError: [Errno 2] No such file or directory: C:\\Python27\\ord.txt
5
  • 4
    Where is ord.txt? I bet it isn't at C:\Python27\ord.txt Commented Feb 4, 2014 at 13:58
  • yes it is there, but it can´t find it, before i was trying without the os.chdir, but even with this it cannot find. Commented Feb 4, 2014 at 14:01
  • Either you mispelled the name of the file or it is somewhere else(check your desktop) . Commented Feb 4, 2014 at 14:02
  • @Azwr I mispelled the name, my file was named as ord.txt.txt that´s why it wasn't working. sorry guys Commented Feb 4, 2014 at 14:31
  • other remark: you don't need to join the path with the current working directory, open() already works relative to the current working directory, so open('ord.txt') is enough (if the file indeed exists in the cwd) Commented Feb 4, 2014 at 15:25

1 Answer 1

1

You have a typo:

os.chdir("C:\\Python27")

or

os.chdir(r"C:\Python27")

will solve it (notice the double backslash \\ in the first option and the r prefix in the second one).

Explanation: You can read here http://docs.python.org/2/reference/lexical_analysis.html#string-literals about escape sequences in Python.

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.