1

I have a very large Python script that I am using pyinstaller with to create an exe. I need to download an XML file but would like to keep the exe as small as possible as it is already getting quite large.

Is there a method within Python to get a file from a URL? I was not able to find anything without an external library

Grady D
  • 1,889
  • 6
  • 30
  • 61

1 Answers1

3

You can use urllib.urlretrieve() that saves the opened page to the specified path.

Alternatively you can open the url with urllib.urlopen() and then write the read file in the binary mode:

import urllib
urllib.urlretrieve(url, destination_path) # First and short way

with open(destination_path, 'wb') as f:   # Equivalent to the first, but longer
    f.write(urllib.urlopen(url).read())
vaultah
  • 44,105
  • 12
  • 114
  • 143
  • 3
    In Python 3, these functions have been moved to [`urllib.request`](http://docs.python.org/3/library/urllib.request.html), so use [`urllib.request.retrieve`](http://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve) and [`urllib.request.urlopen`](http://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen) respectively. – airstrike Mar 10 '14 at 17:39
  • @AndréTerra good note, however the question is tagged `python-2.7` – vaultah Mar 10 '14 at 17:40
  • 1
    -1: `f.write` doesn't accept `urlopen()`. You could use `shutil.copyfileobj(urllib2.urlopen(url), f)` instead. – jfs Mar 10 '14 at 18:03
  • Thanks! Fixed it by passing there a string object returned from `.read()` method – vaultah Mar 10 '14 at 18:06
  • I've removed the downvote. Though `copyfileobj` is better for large files then `.read()` that loads the whole file into memory – jfs Mar 10 '14 at 18:08
  • @Crystal I noticed it was tagged python 2.7, so that's why I added a comment instead of a response ;) I figured many Python 3 developers will still land here after searching on Google or here on SO, and in the long term, we'll all be using Python 3. – airstrike Mar 10 '14 at 18:18