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

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

问题描述

我有以下项目结构

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

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



我有一个限制


  1. 我无法给出完整路径(绝对路径) )constants.cfg因为如果我在不同的PC上运行它应该不进行任何修改

  2. 如果我代表下面的内容,我可以访问该文件。但我不想每次都给予反斜杠

      filename = .. \\\\..\\\ .. \\\\\\\\\\\\\\\\\\\\\\\\\\\\ 

目前我正在做这样的事情。但这只适用于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)

或者如果安装了 setuptools - 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 模块



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



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

  import inspect 
import os
import sys

def get_my_path() :
try:
filename = __file__#我们在模块加载时的位置
除了NameError:#fallback
filename = inspect.getsourcefile(get_my_path)
return os .path.realpath(filename)

#ConfigManager.py的路径
cm_path = get_my_path()
#go 6目录级别上涨
sp_path = reduce(lambda x ,f:f(x),[os.path.dirname] * 6,cm_path)
constants_path = os.path.join(sp_path,conf,constants.cfg)


I have the following project structure

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

How to access constants.cfg from ConfigManager.py.

I have a limitation

  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`
    

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

解决方案

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

import pkgutil

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

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

import pkg_resources

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


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.

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.

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天全站免登陆