简体   繁体   English

使用脚本位置的相对路径时如何在python中打开文件

[英]How to open a file in python when using the relative path from the scripts location

I have a directory Structure as such 我有这样的目录结构

MainFolder/unitTest/test.py
MainFolder/run.py
MainFolder/model/file.py
MainFolder/config/config.conf

Inside file.py i am trying to open a file 在file.py内部,我正在尝试打开文件

f = open('config/config.conf', 'r')

Normally the file.py is called from run.py. 通常,从run.py调用file.py。 The current working directory is that of the run.py. 当前的工作目录是run.py的目录。 so if i want to access the config file . 因此,如果我想访问配置文件。 i go to config folder and then to the file 'config/config.conf' If i want to run it from the unit test i need to go up one level and then into the config folder. 我转到config文件夹,然后转到文件'config/config.conf'如果要从单元测试中运行它,我需要上一层然后进入config文件夹。 '../config/config.conf'

Is there a way that when opening a file , it starts looking for the file from where the file.py is located so that regardless of where the file.py is called from i can access the file as ../config/config.conf 有没有一种方法可以在打开文件时从file.py所在的位置开始查找文件,以便无论我从哪里调用file.py都可以通过../config/config.conf来访问文件

This is going to be hosted on a remote server so i cant give it the full path... 这将被托管在远程服务器上,所以我不能给它完整的路径...

What you need may be to organize your codes in Python modules . 您可能需要在Python模块中组织代码。 It helps you design/access/manage each file in a Pythonic way. 它可以帮助您以Python方式设计/访问/管理每个文件。

To solve your problem, you can work around by setting MainFolder as the current working directory with os.chdir at the beginning of the file.py . 为了解决你的问题,你可以通过设置MainFolder与当前工作目录解决os.chdir在年初file.py It means that you need to have the full path of MainFolder either by using os.path.getcwd in run.py to find out or storing it in config file when deployed. 这意味着您需要拥有MainFolder的完整路径,或者通过在run.py使用os.path.getcwd找出或在部署时将其存储在配置文件中。

Sure, just create a file, eg pwd.py in your project root directory. 当然,只需在项目根目录中创建一个文件,例如pwd.py。

import os

PWD = os.path.dirname(os.path.abspath(__file__))

then in your modules: 然后在您的模块中:

from pwd import PWD

f = open('%s/config/config.conf' % PWD, 'r')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM