How to save a file to a specific directory in python?


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:

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

Asked By: Nitanshu



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

r = requests.get(url)  
with open(r'C:pathtosavefile_name.pdf', 'wb') as f:
Answered By: Cory Kramer

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:

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

See open() function docs for more details.

Answered By: Jonny

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.

Answered By: Billy Ferguson

Here is a quicker solution:

r = requests.get(url) 
open('/path/to/directory/file_name.pdf', 'wb').write(r.content)
Answered By: user19972954
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.