Reputation: 9538
I am trying to download a file to specific directory but I got the file downloaded in the same path of the python code
import requests
from pathlib import Path
def downloadFile(link, destfolder):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'}
r = requests.get(link,headers=headers, stream=True)
filename=link.split('/')[-1]
downloaded_file = open(filename, 'wb')
for chunk in r.iter_content(chunk_size=256):
if chunk:
downloaded_file.write(chunk)
link='http://index-of.es/Python/A.Byte.of.Python.1.92.Swaroop.C.H.2009.pdf'
Path('Files').mkdir(parents=True, exist_ok=True)
downloadFile(link, 'Files')
How can I change the folder that I will download the file into it to be Files
folder ..?
Upvotes: 0
Views: 1098
Reputation: 402
When you are giving the filename try to add the path name like
filename="C:\myfolders\"+filename
this should work kindly let me know if there any issues. Thanks!
Upvotes: 1
Reputation: 7548
simply prepend the folder path to the filename. You can use os.path.join
(for platform independent/robust solution) or simple string manipulation
import requests
from pathlib import Path
import os
def downloadFile(link, destfolder):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'}
r = requests.get(link,headers=headers, stream=True)
filename=link.split('/')[-1]
downloaded_file = open(os.path.join(destfolder, filename), 'wb')
for chunk in r.iter_content(chunk_size=256):
if chunk:
downloaded_file.write(chunk)
link='http://index-of.es/Python/A.Byte.of.Python.1.92.Swaroop.C.H.2009.pdf'
Path('Files').mkdir(parents=True, exist_ok=True)
downloadFile(link, 'Files')
Upvotes: 1