如何使用请求方法将文件下载到新创建的目录



我正在使用请求方法下载一些文件。默认情况下,我可以将文件下载到.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。文件下载工作正常。

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

os.makedirs(Downloadpath, mode=0o777)
# ...
with open(os.path.join(Downloadpath, filename), 'wb') as output_file:
output_file.write(r.data)
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))**

最新更新