gpt4 book ai didi

python : How to access file from different directory

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:49 24 4
gpt4 key购买 nike

我有以下项目结构

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

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

我有一个限制

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

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

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

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

最佳答案

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

import pkgutil

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

或者如果安装了 setuptoolspkg_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 module .

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

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

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 : How to access file from different directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17244406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com