【问题标题】:Python Download files, but they are empty? [closed]Python下载文件,但它们是空的? [关闭]
【发布时间】:2016-03-22 09:57:50
【问题描述】:

我正在尝试使用以下代码使用 Python (2.7) 下载文件 - 但为什么我得到空文件? 有人能指出“泄漏”吗?我错过了什么?

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

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

【问题讨论】:

  • 因为您打开一个文件,然后立即关闭它。你的意思是在两者之间写一些数据吗?
  • 是的。我要数据之间如何实现呢?谷歌搜索 - 没有爱
  • 您所要做的就是搜索 python 下载文件,那里有 加载 个示例。这不是比在 Stack Overflow 上提问更容易吗?
  • 你没有读过url,也没有写入文件

标签: python download urllib2


【解决方案1】:

您当前的代码是:

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

【讨论】:

  • 感谢大家的 cmets 和回答/希望这能提高我的谷歌技能
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2014-06-07
  • 2018-02-26
  • 2020-06-23
  • 2017-08-06
  • 1970-01-01
相关资源
最近更新 更多