gpt4 book ai didi

python - 写入 Pickle 文件时出现 FileNotFoundError

转载 作者:行者123 更新时间:2023-12-04 07:50:26 25 4
gpt4 key购买 nike

我在 list 中获取某个目录中的所有文件名,并想将此列表写入 pickle文件。这是我正在使用的代码:

import _pickle as pickle
with open(filepath+'filenames.pkl', 'wb') as f:
pickle.dump(filenames, f)
这给了我以下错误:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-32-c59e6889d2fe> in <module>()
1 import _pickle as pickle
----> 2 with open(dpath+'filenames.pkl', 'wb') as f:
3 pickle.dump(filenames, f)

FileNotFoundError: [Errno 2] No such file or directory: '/data/train/filenames.pkl'
我应该创建这个文件。为什么这个文件是预期的?
(我使用的是 Python 3.6。)

最佳答案

在你的情况下很可能 /data/train/目录不存在

我试过这段代码并得到同样的错误:

import pickle as pickle
filenames='sadasdas'
with open('/tmp/not_exist/filenames.pkl', 'wb') as f:
pickle.dump(filenames, f)

输出:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-7-6a22c2148796> in <module>()
1 import pickle as pickle
2 filenames='sadasdas'
----> 3 with open('/tmp/not_exist/filenames.pkl', 'wb') as f:
4 pickle.dump(filenames, f)

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/not_exist/filenames.pkl'

您可以通过在写入文件之前确保目录存在来处理此问题:执行相同操作的编程方法是这样的
import os
filename = "/tmp/not_exist/filenames.pkl"
os.makedirs(os.path.dirname(filename), exist_ok=True)
data = 'sadasdas'
with open('/tmp/not_exist/filenames.pkl', 'wb') as f:
pickle.dump(data, f)

引用: https://stackoverflow.com/a/12517490/3027854

关于python - 写入 Pickle 文件时出现 FileNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42604024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com