Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a config file using python

Tags:

python

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

path1 = "D:\test1\first" path2 = "D:\test2\second" path3 = "D:\test2\third" 

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

like image 747
a4aravind Avatar asked Oct 15 '13 10:10

a4aravind


People also ask

HOW include config file in Python?

Python can have config files with all settings needed by the application dynamically or periodically. Python config files have the extension as . ini. We'll use VS Code (Visual Studio Code) to create a main method that uses config file to read the configurations and then print on the console.

How do I read a CFG file?

Because they are plain text documents, you can open mugen. cfg or any other M.U.G.E.N CFG file with any text editor. In Windows, you can open a CFG file with Microsoft Notepad or Microsoft WordPad. In macOS, you can use Apple TextEdit.


1 Answers

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

[your-config] path1 = "D:\test1\first" path2 = "D:\test2\second" path3 = "D:\test2\third" 

Then in your code you can use the config parser.

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

As human.js noted in his comment, in Python 3, ConfigParser has been renamed configparser. See Python 3 ImportError: No module named 'ConfigParser' for more details.

like image 68
Kobi K Avatar answered Sep 21 '22 08:09

Kobi K