【问题标题】:How to download files using request method to a newly created directory?如何使用请求方法将文件下载到新创建的目录?
【发布时间】:2020-02-21 11:11:58
【问题描述】:

我正在使用请求方法下载一些文件。默认情况下,我可以将文件下载到 .py 文件所在的目录。但我想将其更改为一些自定义路径。使用以下代码,我可以根据需要创建目录。但我不知道如何将下载路径设置为我新创建的目录。有人可以帮忙吗?

now = datetime.datetime.now()
Downloadpath = now.strftime("%Y_%m_%d-%H%M")
print("Making directory " + Downloadpath)
os.makedirs(Downloadpath, mode=0o777)

编辑:下载文件的代码如下

 r = https.request('GET', urlname, headers={'Authorization': access_token})

            if r.status != 200:
                return False
            filename = urlname.split('/')[-1]
            filename += '.ext.zip'
            with open(filename, 'wb') as output_file:
                output_file.write(r.data) 

也没有。文件数约为 200-300。文件下载工作正常。

【问题讨论】:

  • 请出示下载文件的代码。
  • 我在问题中添加了下载文件的代码。请检查。

标签: python python-3.x directory download


【解决方案1】:

在将下载的数据写入文件时,不要单独使用文件名,只需将其与生成目录的路径结合起来:

os.makedirs(Downloadpath, mode=0o777)

# ...

with open(os.path.join(Downloadpath, filename), 'wb') as output_file:
    output_file.write(r.data)

【讨论】:

  • 非常感谢。现在我可以将文件下载到新目录了。
【解决方案2】:
import os,datetime

currentDir =os.path.abspath(os.getcwd())+"/"+datetime.datetime.now().strftime("%Y_%m_%d-%H%M")
os.mkdir(currentDir)

r = https.request('GET', urlname, headers={'Authorization': access_token})

if r.status != 200:
    return False
filename = urlname.split('/')[-1]
filename += '.ext.zip'
with open((currentDir+'/'+filename), 'wb') as output_file:
    output_file.write(r.data) 

Above code will work fine for you , 
Only thing you need to do is, just assign the path where **open((currentDir+'/'+filename))**

【讨论】:

    猜你喜欢
    • 2017-03-15
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    相关资源
    最近更新 更多