Python 下载文件,但文件是空的?

Python Download files, but they are empty?

我正在尝试使用下面的代码使用 Python (2.7) 下载文件 - 但为什么我得到空文件? 有人可以指出 "leak" - 我错过了什么吗?

如何获取包含文本的原始文件?

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()   

您当前的密码是:

  1. 从未真正发送过 HTTP 请求; Request()只是构建一个请求,urlopen()实际发送它;
  2. 从来没有真正用 f.write() 向文件写入任何东西,你只是打开一个文件并立即关闭它。

完整示例可能如下所示:

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()