Python:如何从不同目录访问文件 [英] Python : How to access file from different directory

查看:17
本文介绍了Python:如何从不同目录访问文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下项目结构

SampleProject
     com
       python
          example
             source
                utils
                   ConfigManager.py
     conf
        constants.cfg

如何从 ConfigManager.py 访问 constants.cfg.

How to access constants.cfg from ConfigManager.py.

我有一个限制

  1. 我无法给出 constants.cfg 的完整路径(绝对路径),因为如果我在不同的 PC 上运行它应该无需任何修改即可工作
  2. 此外,如果我代表以下内容,我可以访问该文件.但我不想每次都给回斜线

  1. I can not give full path(absolute path) of constants.cfg because if I run in different PC it should work with out any modification
  2. Also if I represent something like below, I can access the file. But I don't want to give back slash every time

filename = ..\..\..\..\..\..\constants.cfg`

目前我正在做这样的事情.但这仅在constants.cfg 和ConfigManager.py 位于同一目录时有效

Currently I am doing something like this. But this works only when constants.cfg and ConfigManager.py are in same directory

currentDir =  os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
file = open(os.path.join(currentDir,'constants.cfg'))     

推荐答案

如果 conf 是一个 Python 包,那么你可以使用 pkgutil.get_data():

If conf is a Python package then you could use pkgutil.get_data():

import pkgutil

data = pkgutil.get_data("conf", "constants.cfg")

或者如果安装了 setuptools<代码>pkg_resources.resource_string():

Or if setuptools is installed – pkg_resources.resource_string():

import pkg_resources

data = pkg_resources.resource_string('conf', 'constants.cfg')

<小时>

如果 constants.cfg 不在包中,则将其路径作为命令行参数传递,或将其设置在环境变量中,例如 CONFIG_MANAGER_CONSTANTS_PATH,或读取来自一组固定的默认路径,例如 os.path.expanduser("~/.config/ConfigManager/constants.cfg").要找到放置用户数据的位置,您可以使用 appdirs 模块.


If constants.cfg is not in a package then pass its path as a command-line parameter, or set it in an environment variable e.g., CONFIG_MANAGER_CONSTANTS_PATH, or read from a fixed set of default paths e.g., os.path.expanduser("~/.config/ConfigManager/constants.cfg"). To find a place where to put user data, you could use appdirs module.

如果您可以从不同目录运行 ConfigManager.py,则不能使用返回当前工作目录的 os.getcwd().相对路径 "../../..." 不会因为同样的原因工作.

You can't use os.getcwd() that returns current working directory if you may run ConfigManager.py from different directories. Relative path "../../..." won't work for the same reason.

如果你确定 ConfigManager.pyconstants.cfg 在文件系统中的相对位置不会改变:

If you are certain that the relative position of ConfigManager.py and constants.cfg in the filesystem won't change:

import inspect
import os
import sys

def get_my_path():
    try:
        filename = __file__ # where we were when the module was loaded
    except NameError: # fallback
        filename = inspect.getsourcefile(get_my_path)
    return os.path.realpath(filename)

# path to ConfigManager.py
cm_path = get_my_path()
# go 6 directory levels up
sp_path = reduce(lambda x, f: f(x), [os.path.dirname]*6, cm_path)
constants_path = os.path.join(sp_path, "conf", "constants.cfg")

这篇关于Python:如何从不同目录访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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