45

Currently, I am using this code to save a downloaded file but it is placing them in the same folder where it is being run from.

r = requests.get(url)  
with open('file_name.pdf', 'wb') as f:
    f.write(r.content)

How would I save the downloaded file to another directory of my choice?

mit
  • 11,083
  • 11
  • 50
  • 74
Nitanshu
  • 786
  • 2
  • 9
  • 22

4 Answers4

108

Or if in Linux, try:

# To save to an absolute path.
r = requests.get(url)  
with open('/path/I/want/to/save/file/to/file_name.pdf', 'wb') as f:
    f.write(r.content)


# To save to a relative path.
r = requests.get(url)  
with open('folder1/folder2/file_name.pdf', 'wb') as f:
    f.write(r.content)

See open() function docs for more details.

Jonny
  • 3,807
  • 8
  • 31
  • 48
  • what about if it's a downloaded zip folder and you want to save it in a directory – medev21 Feb 14 '18 at 20:07
  • The above would also work to save a zip file (the path defined as as a URL) to a specific directory (e.g. `/path/I/want/to/save/file/to/archive.zip`). Or do you mean to download an archive from a URL and extract it to a folder? – Jonny Feb 16 '18 at 12:48
10

You can just give open a full file path or a relative file path

r = requests.get(url)  
with open(r'C:\path\to\save\file_name.pdf', 'wb') as f:
    f.write(r.content)
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

As long as you have access to the directory you can simply change your file_name.pdf' to '/path_to_directory_you_want_to_save/file_name.pdf' and that should do what you want.

Billy Ferguson
  • 1,429
  • 11
  • 23
-2

Here is a quicker solution:

r = requests.get(url) 
open('/path/to/directory/file_name.pdf', 'wb').write(r.content)