Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

How to read a config file using python

I have a config file abc.txt which looks somewhat like:

path1 = "D:est1first"
path2 = "D:est2second"
path3 = "D:est2hird"

I want to read these paths from the abc.txt to use it in my program to avoid hard coding.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order to use my example, your file "abc.txt" needs to look like:

[your-config]
path1 = "D:est1first"
path2 = "D:est2second"
path3 = "D:est2hird"

Then in your software you can use the config parser:

import ConfigParser

and then in your code:

 configParser = ConfigParser.RawConfigParser()   
 configFilePath = r'c:abc.txt'
 configParser.read(configFilePath)

Use case:

self.path = configParser.get('your-config', 'path1')

*Edit (@human.js)

In Python 3, ConfigParser is renamed to configparser (as described here)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...