Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python saving xml from webservice

Tags:

python

I'm using a webservice to get a certain xml file from it. It works fine with urllib2 I get the xml as fileobject. So I want to know what would be the fastest way to store that somewhere in memory or not even store just parse it.

I tried iterparse on that object and it takes too long unless I save it first in file, then iterparse takes much less time.

So now I'm using this code to store it locally first and then do with that file what I want, and I would like to know is there a fastest way of doing it, fastest way of storing files.

url = "webservice"
s = urllib2.urlopen(url)

file = open("export.xml",'wb+')
for line in s:
    file.write(line)

Thanks

like image 941
iblazevic Avatar asked Jan 27 '26 18:01

iblazevic


2 Answers

You don't need to write line-by-line. Just write the whole thing in one go:

>>> import urllib2
>>> url = "webservice"
>>> s = urllib2.urlopen(url)
>>> contents = s.read()
>>> file = open("export.xml", 'w')
>>> file.write(contents)
>>> file.close()
like image 155
beerbajay Avatar answered Jan 30 '26 11:01

beerbajay


You can store it in a string:

content = s.read()

or a StringIO if you need file-like interface

content = cStringIO.StringIO()
content.write(s.read)
like image 44
Kien Truong Avatar answered Jan 30 '26 12:01

Kien Truong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!