-2

I'm trying to download file with Python (2.7) using code below - But why I get empty file? Can somebody point me the "leak" - what am I missing?

How to get original file with text inside?

import urllib2

url = 'https://www.dropbox.com/s/splz3vk9pl1tbgz/test.txt?dl=0'
user_agent = 'Mozilla 5.0 (Windows 7; Win64; x64)'
file_name = "test.txt"
u = urllib2.Request(url, headers = {'User-Agent' : user_agent})
f = open(file_name, 'wb')
f.close()   
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
David Graig
  • 153
  • 1
  • 9

1 Answers1

1

Your current code is:

  1. never actually sending out the HTTP request; Request() just builds a request, urlopen() actually sends it;
  2. never actually writing anything to the file with f.write(), you're just opening a file and immediately closing it.

A full example might look like:

import urllib2

url = 'https://www.dropbox.com/s/splz3vk9pl1tbgz/test.txt?dl=0'
user_agent = 'Mozilla 5.0 (Windows 7; Win64; x64)'
file_name = "test.txt"
u = urllib2.Request(url, headers = {'User-Agent' : user_agent})

# Actually make the request
req = urllib2.urlopen(u)

f = open(file_name, 'wb')

# Read data from the request, and write it to the file
f.write(req.read())

f.close()
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146