python - IO错误: [Errno 2] No such file or directory/in package

标签 python python-module

下面是我的 init.py,位于 pkg/settings 下

import yaml
import os

def Keypairs():
    print os.path.dirname(os.path.realpath(__file__))
    with open('keypairs.yaml') as f:
        return yaml.load(f)

我运行包:python -m pkg.test.first 它有一个相对导入:

from ..settings    import Keypairs    
print Keypairs()

但我明白了

IOError: [Errno 2] No such file or directory: 'keypairs.yaml'

虽然结构是:

pkg/
  __init__.py
  settings/
    __init__.py
    keypairs.yaml
  test/
    __init__.py
    first.py

我在搞乱目录什么?

如果我将 __init__.py (位于设置中)作为脚本运行,它会找到该文件。

最佳答案

看来,由于我将文件作为包运行,因此它将包所在的目录作为父目录。

所以你需要通过

basepath = os.path.dirname(__file__)
keypairs = os.path.abspath(os.path.join(basepath, "keypairs.yaml"))
with open(keypairs,'r') as f:
    return yaml.load(f)

或者如果你想要绝对的:

with open("pkg/settings/keypairs.yaml",'r') as f:

在@yorodm的帮助下最干净的方式

with open(os.path.join(os.path.dirname(__file__),'keypairs.yaml')) as f:
    return yaml.load(f)

关于python - IO错误: [Errno 2] No such file or directory/in package,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23090151/

相关文章:

python - 将样式应用于 pandas DataFrame row-wise

Python 最佳实践在子模块中导入子模块

python - 试图找出为什么我在第 12 行收到打印语法错误

python - 如何重定向 web.py 中的输出

python - 在 3.3 中加载 python 模块时,我用什么代替 PyString_AsString

python - 在 Python 中中止模块的执行

Python:在一系列脚本之间共享通用代码

python - __init__.py 找不到本地模块

python - 使用 psexec 在远程机器上运行 AutoIt

python - 服务器和客户端都是python脚本,有没有办法在不改变系统日期的情况下同步服务器和客户端时间?