Python 如何将从请求下载的文件保存到另一个目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44699682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save a file downloaded from requests to another directory?
提问by Nitanshu
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)
回答by Jonny
Or if in Linux, try:
或者,如果在 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)
See open() functiondocs for more details.
有关更多详细信息,请参阅open() 函数文档。
回答by Cory Kramer
You can just give open
a full file path or a relative file path
您可以只提供open
完整的文件路径或相对文件路径
r = requests.get(url)
with open(r'C:\path\to\save\file_name.pdf', 'wb') as f:
f.write(r.content)
回答by Billy Ferguson
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.
只要您可以访问的目录,你可以简单地改变你file_name.pdf'
对'/path_to_directory_you_want_to_save/file_name.pdf'
和应该做你想要什么。