【问题标题】:How to download the file from remote source and saving it into local folder using Python如何从远程源下载文件并使用 Python 将其保存到本地文件夹中
【发布时间】:2017-09-12 10:21:54
【问题描述】:

我需要一个帮助。我需要从远程源下载文件并使用 Python 将其存储到本地文件夹中。我在下面解释我的代码。

def downloadfile(request):
    """ This function helps to download the file from remote site"""

    if request.method == 'POST':
        URL = request.POST.get('file') #i.e-http://koolfeedback.com/beta/about-us.php
        filename = "status"
        with open(filename,'wb') as fyl:
            fyl.write(urllib2.urlopen(URL).read())
            fyl.close()

这里我需要下载页面并使用zip格式存储到本地download文件夹中。请帮助我。

【问题讨论】:

  • 这里的request是什么意思?
  • 我已经提到了post数据。 request.POST.get('file')=http://koolfeedback.com/beta/about-us.php。此 URL 来自表单参数,我需要下载该确切页面并将其存储到本地文件夹中。
  • 看起来您已经将该 URL 中的内容保存在名为“status”的文件中。是否要使用 DEFLATE 压缩压缩此文件并将其移动到名为 download 的文件夹中?
  • 是的,我需要将它移动到项目目录中的下载文件夹中。
  • 你在做request.POST.get...request 对象来自哪里?你在用 django 吗?

标签: python django urllib2


【解决方案1】:

您可能希望使用urllib 函数urlretrieve 而不是urlopen,它用于打开远程文件(例如远程服务器上的文本文件,您可以从中读取文本,而不是您想要读取的文件)下载)。

另见:https://stackoverflow.com/a/22682/6328995

【讨论】:

  • 不,我的主要目的是包含远程文件。
  • 然后链接它?
  • 你试过了吗:fyl.write((urllib2.urlopen(URL)).read())?函数的嵌套可能会导致问题。另外,尝试用print(urllib2.urlopen(URL)).read()) 替换这一行,看看它是否真的在正确读取文件
【解决方案2】:

如果你正在使用 django 类似的东西;

folder_to_store = "path/to/folder"
full_filename = os.path.join(folder_to_store, request.FILES['file'].name)
fout = open(full_filename, 'wb+')
for chunk in fout.chunks():
    fout.write(chunk)
fout.close()

【讨论】:

    猜你喜欢
    • 2019-11-18
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多