Python: 如何从不同目录访问文件

2024-04-29 14:26:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下项目结构

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'))     

Tags: path项目pysampleprojectcomsourceosexample
3条回答

您可以在Python 3.0+中使用pathlib

这将获取包含在SampleProject文件夹中的任何文件的路径 跨不同的平台。

from pathlib import Path
def get_file(path):
    """
    returns the absolute path of a file
    :var
    str path
        the file path within the working dir
    :returns
    PureWindowsPath or PurePosixPath object
        type depends on the operating system in use
    """
    def get_project_root() -> Path:
    """Returns project root folder."""
    return Path(__file__).parent.parent

    return get_project_root().joinpath(path)

然后用文件路径作为参数调用函数:

filePath = get_file('com/python/example/source/utils/configManager.py')

然后是通常的程序:

while open(filePath) as f:
    <DO YOUR THING>

如果在项目树的根目录中有某个模块,请说config_loader.py,如下所示:

import os

def get_config_path():
    relative_path = 'conf/constants.cfg'
    current_dir = os.getcwd()
    return os.join(current_dir, relative_path)

然后在ConfigManager.py或任何其他需要配置的模块中:

import config_loader

file_path = config_loader.get_config_path()
config_file = open(file_path)

你甚至可以让你的config_loader.py返回配置文件。

如果conf是一个Python包,那么可以使用^{}

import pkgutil

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

或者如果安装了setuptools^{}

import pkg_resources

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

如果constants.cfg不在包中,则将其路径作为命令行参数传递,或在环境变量(例如CONFIG_MANAGER_CONSTANTS_PATH)中设置,或从固定的默认路径集(例如os.path.expanduser("~/.config/ConfigManager/constants.cfg"))中读取。要找到放置用户数据的位置,可以使用^{} 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")

相关问题 更多 >