简体   繁体   中英

Where should I place a config.txt in my python project

The project folder hierarchy looks like

ProjectName
   ->src
      ->Project.sikuli
          ->myFile.py
          ->config.txt

Now, I have all the settings variables being stores in my config.txt and I'm using ConfigParser to fetch the values from it. The reason why I'm using this config file here is that, when this sikuli script is moved to another machine for running I can just change the values in it (like paths, username, password) rather than editing the main python script 'myFile.py'.
But the issue I'm encountering now is that I don't want the config file to be placed some where outside the project so that in my script when I try to fetch the values from it, I don't have to mention the absolute path again in the myFile.txt like:

configParser = ConfigParser.RawConfigParser()
configfilePath = r'D:\MyWorkspace\ProjectName\src\Project.sikuli\config.txt'

Instead I want to have the relative path here so that while migrating the project from machine to machine I don't have to do any manipulations in the main script 'myFile.py'

So what I'm trying to achieve is like: I should be able to refer the config.txt file by giving it's relative path:

configfilePath = r'D:\MyWorkspace\ProjectName\src\Project.sikuli\config.txt'

如果将其与myFile.py保留在同一文件夹中,那么在该Python脚本中,您可以使用以下内容:

configfilePath = os.path.join(os.path.dirname(__file__), 'config.txt')

最佳方法是像在示例中所做的那样,将文件放入 .sikuli捆绑包中,然后按以下方式获取文件的路径:

configFilePath = os.path.join(getBundlePath(), 'config.txt')

I know you can fetch variables and value from a python file by importing it...

import config

I would put it in the root repertory of the project

First, get the path of the currently executed python script:

myPath = os.path.abspath(os.path.dirname(sys.argv[0]))

and then do a join of myPath and 'config.txt'

configfilePath = os.path.join(myPath, 'config.txt')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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