[英]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:
f.write(r.content)
How would I save the downloaded file to another directory of my choice?如何将下载的文件保存到我选择的另一个目录?
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() function docs for more details. 有关更多详细信息,请参阅open()函数文档。
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)
只要您可以访问该目录,就可以将file_name.pdf'
更改为'/path_to_directory_you_want_to_save/file_name.pdf'
file_name.pdf'
'/path_to_directory_you_want_to_save/file_name.pdf'
,这应该可以执行您想要的操作。
Here is a quicker solution:这是一个更快的解决方案:
r = requests.get(url)
open('/path/to/directory/file_name.pdf', 'wb').write(r.content)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.