用python如何访问文件目录_Python:如何从不同的目录访问文件

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值