如何将从请求下载的文件保存到另一个目录?

Nit*_*shu 4 python python-3.x python-requests

目前,我使用它来下载文件,但它将它们放在运行它的同一文件夹中,但是如何将下载的文件保存到我选择的另一个目录中.

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

Jon*_*nny 20

或者如果在Linux中,请尝试:

# 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)
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅open()函数文档.


Cor*_*mer 6

您可以只提供open完整的文件路径或相对文件路径

r = requests.get(url)  
with open(r'C:\path\to\save\file_name.pdf', 'wb') as f:
    f.write(r.content)
Run Code Online (Sandbox Code Playgroud)