Python软件包中的相对文件路径 [英] Relative file paths in Python packages

查看:93
本文介绍了Python软件包中的相对文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何相对于包目录引用文件?

How do I reference a file relatively to a package's directory?

我的目录结构是:


    /foo
     package1/
      resources/
      __init__.py
     package2/
      resources/
      __init__.py
     script.py

script.py导入软件包package1package2.尽管可以通过系统上的任何其他脚本导入软件包.我应该如何引用内部的资源,例如package1,以确保在os.path.curdir是任意的情况下它可以工作?

script.py imports packages package1 and package2. Although the packages can be imported by any other script on the system. How should I reference resources inside, say, package1 to ensure it would work in case os.path.curdir is arbitrary?

推荐答案

如果要引用foo/package1/resources文件夹中的文件,则需要使用模块的__file__变量.内foo/package1/__init__.py:

If you want to reference files from the foo/package1/resources folder you would want to use the __file__ variable of the module. Inside foo/package1/__init__.py:

from os import path
resources_dir = path.join(path.dirname(__file__), 'resources')

这篇关于Python软件包中的相对文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆