0

I'm trying to print the lines present in the url file however,I'm getting an error that says:

    with html as ins:
    AttributeError: __exit__

Below posted is my code

  import urllib2

  response = urllib2.urlopen('------------------')

  html = response.read()
  counter = 0;
  with html as ins:
  array = []
  for line in ins:
     counter = counter+1
     print "cluster number is:", counter  
     print line  
user3787061
  • 61
  • 1
  • 8

1 Answers1

1

If you want to write the bytes from the url as is (no decoding/encoding):

#!/usr/bin/env python2
import urllib2
import shutil
import sys
from contextlib import closing

with closing(urllib2.urlopen(url)) as response:
    shutil.copyfileobj(response, sys.stdout)

It expects that the character encoding used by response is the same character encoding your terminal uses otherwise you'll see mojibake. See A good way to get the charset/encoding of an HTTP response in Python.


Your code in the question contains multiple errors e.g.:

  • wrong indentation
  • it tries to use a str object as a context manager that leads to AttributeError (__exit__ method is not defined) because str object does not implement the context manager protocol
  • for line in ins is misleading: iterating over a string yields characters, not lines.
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • @Sebastian I'm looking for extracting the values and copying them in an array and print them line by line – user3787061 Feb 12 '15 at 02:27
  • @user3787061: Split your problem into a sequence of smaller tasks that could be understood easily e.g., 1. what do you want to print line-by-line? (is it the content of the url? what is it? is it a byte stream with a json text or with an html document or with a xml document?) 2. What does it mean *"extracting the values"* -- provide an example input as a string and the corresponding output array. Update your question. Do not put additional info in the comments. – jfs Feb 12 '15 at 02:36