【问题标题】:Python : How to access file from different directoryPython:如何从不同的目录访问文件
【发布时间】:2013-06-19 03:01:18
【问题描述】:

我有以下项目结构

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

【问题讨论】:

  • 不知道有没有办法解决这个问题,但是要获取当前目录,可以使用os.getcwd()。
  • SamplePoject 是否包含 _init_.py 文件? constants.cfg 是特定格式,还是 Python 文件?

标签: python python-2.7 import python-import pythonpath


【解决方案1】:

您可以在 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)

然后只需使用 file_path 作为参数调用该函数:

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

然后是通常的程序:

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

【讨论】:

    【解决方案2】:

    如果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")
    

    【讨论】:

      【解决方案3】:

      如果您在项目树的根目录中有一些模块,请说 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 只返回配置文件。

      【讨论】:

      • getcwd() 仅在您从 SampleProject 目录运行 ConfigManager.py 时才有效。
      猜你喜欢
      • 2019-06-25
      • 1970-01-01
      • 2011-01-25
      • 2021-03-11
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      相关资源
      最近更新 更多