How to save a file to a specific directory in python?
Question:
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?
Answers:
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:
f.write(r.content)
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.
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.
Here is a quicker solution:
r = requests.get(url)
open('/path/to/directory/file_name.pdf', 'wb').write(r.content)
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?
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:
f.write(r.content)
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.
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.
Here is a quicker solution:
r = requests.get(url)
open('/path/to/directory/file_name.pdf', 'wb').write(r.content)