How to save a file downloaded from requests to ano

2020-08-24 13:18发布

问题:

Currently, I am using this to download a file but it is placing them in the same folder where it is being run from, but how would I save the downloaded file to another directory of my choice.

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

回答1:

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.



回答2:

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)


回答3:

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.