FileNotFoundError while writing to a Pickle file
我在一个
1 2 3 | import _pickle as pickle with open(filepath+'filenames.pkl', 'wb') as f: pickle.dump(filenames, f) |
这给了我以下错误:
1 2 3 4 5 6 7 8 | --------------------------------------------------------------------------- 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' |
我应该创建这个文件,为什么已经需要这个文件?
(我用的是
短暂性脑缺血发作
在您的情况下,很可能
我尝试了这个代码,但得到了相同的错误:
1 2 3 4 | import pickle as pickle filenames='sadasdas' with open('/tmp/not_exist/filenames.pkl', 'wb') as f: pickle.dump(filenames, f) |
输出:
1 2 3 4 5 6 7 8 9 | --------------------------------------------------------------------------- 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' |
在写入文件之前,您可以通过确保目录存在来处理这个问题:编程方法也是这样做的吗?
1 2 3 4 5 6 | 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
我必须从Windows10上的WindowsDefender中设置"受控文件夹访问"。
其他防病毒/防火墙可能具有相同的效果。
https://support.microsoft.com/en-us/help/4046851/windows-10-controlled-folder-access-windows-defender-security-center
我在使用相对路径名(和符号链接)编写时遇到了类似的问题。目录勉强存在,但仍在引发filenotfounderror。
当我切换到使用绝对路径时问题就消失了
1 2 3 | abspath = pathlib.Path(filename).absolute() with open(str(abspath), 'wb') as f: pickle.dump(thing_to_pickle, f) |