简体   繁体   English

如何将文件保存到 python 中的特定目录?

[英]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.

相关问题 如何将文件保存到特定目录并在python中选择文件名? - How to save a file to a specific directory and choose the file's name in python? 如何在python中使用硒将下载的文件保存到特定的相对目录 - How to save a downloaded file to a specific relative directory with selenium in python 如何将录制的 .wav 文件保存到 python 中的特定目录 - How do you save a recorded .wav file to a specific directory in python Selenium 如何将屏幕截图保存到 Python 中的特定目录 - Selenium how to save screenshot to specific directory in Python 如何在特定目录中制作文件 python - How to make a file in a specific directory python 如何使用 OpenCV VideoWriter 将视频保存到特定目录——python - How to save a video using OpenCV VideoWriter to a specific directory -- python 如何让目录选择将csv文件保存在python中? - How to let choose the directory to save csv file in python? 如何在python中读取目录的所有文件并将文件数据保存在字典中 - How to read all the files of a directory in python and save file data in a dictionary Python:如何将文件保存在其他目录中? - Python: how do I save a file in a different directory? 如何将合并的文本文件保存到python的子目录中? - How to save merged text file into a sub-directory in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM