python中的文件位置错误

时间:2017-05-03 06:37:07

标签: python python-2.7 numpy

我正在尝试在我的VQA项目中实现skipthoughts向量,但我在从指定位置读取文件时遇到问题。这是一段跳码代码

path_to_models = 'C:/Users/Downloads/Stacked Attention Networks/skip_thought'
path_to_tables = 'C:/Users/Downloads/Stacked Attention Networks/skip_thought'

path_to_umodel = path_to_models + 'uni_skip.npz'
path_to_bmodel = path_to_models + 'bi_skip.npz'

def load_model():
    """
    Load the model with saved tables
    """
    # Load model options
    print ('Loading model parameters...')
    with open('%s.pkl'%path_to_umodel, 'rb') as f:
        uoptions = pkl.load(f)
    with open('%s.pkl'%path_to_bmodel, 'rb') as f:
        boptions = pkl.load(f)

当我调用skipthoughts.py

时,这是错误消息
File "C:/Users/Downloads/Stacked Attention 
Networks/skip_thought/new_skip_thought.py", line 11, in <module>
model = skipthoughts.load_model()

File "skipthoughts.py", line 37, in load_model
with open('%s.pkl'%path_to_umodel, 'rb') as f:

IOError: [Errno 2] No such file or directory: 
'C:/Users/Downloads/Stacked Attention Networks/skip_thoughtuni_skip.npz.pkl'

文件位置不正确

  

&#39; C:/ Users / Downloads / Stacked Attention Networks / skip_thoughtuni_skip.npz.pkl &#39;

应该是

  

&#39; C:/ Users / Downloads / Stacked Attention Networks / skip_thought / uni_skip.npz.pkl &#39;

2 个答案:

答案 0 :(得分:1)

您需要使用os.path.join,如下所示:

import os

path_to_models = 'C:/Users/Downloads/Stacked Attention Networks/skip_thought'
path_to_tables = 'C:/Users/Downloads/Stacked Attention Networks/skip_thought'

path_to_umodel = os.path.join(path_to_models, 'uni_skip.npz')
path_to_bmodel = os.path.join(path_to_models, 'bi_skip.npz')

答案 1 :(得分:1)

程序中唯一的问题是path_to_umodelpath_to_bmodel中保存的错误文件路径。 要解决此问题,您可以通过在其末尾添加path_to_models来修改变量path_to_tables/

path_to_models = 'C:/Users/Downloads/Stacked Attention Networks/skip_thought/'

path_to_tables = 'C:/Users/Downloads/Stacked Attention Networks/skip_thought/'

或者您可以在/uni_skip.npz的开头添加bi_skip.npz,然后这些行变为:

path_to_umodel = path_to_models + '/uni_skip.npz'
path_to_bmodel = path_to_models + '/bi_skip.npz'

更好的是,您可以使用python&#39; os模块中内置的os.path.join函数。 只需import os在程序开头,并将其用作:

path_to_umodel = os.path.join(path_to_models, os.sep, 'uni_skip.npz')
path_to_bmodel = os.path.join(path_to_models, os.sep, 'bi_skip.npz')

此处,os.sep是运行代码的平台上使用的文件分隔符。 对于Windows,它是\,对于linux和unix,它是/。 最好使用os.sep而不是硬编码某些值。