Normally, executing the following code will pickle an object to a file in my current
directory:
fp = open('somefile.txt', 'wb')
pickle.dump(object, fp)
How do I re-direct the output from pickle.dump
to a different directory?
Normally, executing the following code will pickle an object to a file in my current
directory:
fp = open('somefile.txt', 'wb')
pickle.dump(object, fp)
How do I re-direct the output from pickle.dump
to a different directory?
with open('/full/path/to/file', 'wb') as f:
pickle.dump(object, f)
pathlib 和 with 的组合怎么样,我认为它更灵活,更安全。
# from python 3.4
from pathlib import Path
my_path = Path("{path to you want to set root like . or ~}") / "path" / "to" / "file"
with my_path.open('wb') as fp:
pickle.dump(object, fp)
如果您希望将文件保存到位于包含您的代码的文件夹内的子文件夹中,您可以使用 pathlib 模块。这将允许代码工作,即使它的位置在您的计算机上移动,或者您的代码被添加到不同的机器。
导入模块:
from pathlib import Path
将 root 设置为等于您当前的文件夹:
root = Path(".")
创建子文件夹和文件名的路径:
my_path = root / "my_sub_folder" / "my_file_name"
打开您的文件,将数据转储到您的文件,关闭您的文件:
my_file = open(my_path, 'wb')
my_file = pickle.dump("data_to_save", my_file)
my_file.close()