Reading config file that does not begin with section - python

I have config file that looks something like:
#some text
host=abc
context=/abc
user=abc
pw=abc
#some text
[dev]
host=abc
context=/abc
user=abc
pw=abc
[acc]
host=abc
context=/abc
user=abc
pw=abc
I would like to parse the cfg file with ConfigParser in Python 2.7. The problem is that the cfg file does not start with the section. I cannot delete the text lines before the sections. Is there any workaround for that?

Inject a section header of your choice.
import ConfigParser
import StringIO
def add_header(cfg, hdr="DEFAULT"):
s = StringIO.StringIO()
s.write("[{}]\n".format(hdr))
for line in cfg:
s.write(line)
s.seek(0)
return s
parser = ConfigParser.ConfigParser()
with open('file.cfg') as cfg:
parser.readfp(add_header(cfg, "foo"))

Related

Modifying pi-config values using python

I'm trying to create a python script that will toggle my pi3 /boot/config.txt files gpu_mem=156 parameter for desktop and game mode. I have tried looking into ConfigParser but the config file I'm using uses a simpler format of simply:
var1=value0
var2=value1
I would appreciate some advice.
If you are using a text file to store your config you can parse it like
with open('config.txt', 'r') as config:
for line in config.read().splitlines():
var, val = line.split('=')
print var, val
But if you are storing your config that can be parsed by ConfigParser in the following format
[global]
var1=value0
var2=value1
Then you can parse it with ConfigParser like so
import ConfigParser
config_parser = ConfigParser.ConfigParser()
config_parser.read('config.txt')
print config_parser.get('global', 'var1')

Read Value from Config File Python

I have a file .env file contain 5 lines
DB_HOST=http://localhost/
DB_DATABASE=bheng-local
DB_USERNAME=root
DB_PASSWORD=1234567890
UNIX_SOCKET=/tmp/mysql.sock
I want to write python to grab the value of DB_DATABASE
I want this bheng-local
I would have use
import linecache
print linecache.getline('.env', 2)
But some people might change the order of the cofigs, that's why linecache is not my option.
I am not sure how to check for only some strings match but all the entire line, and grab the value after the =.
I'm kind of stuck here :
file = open('.env', "r")
read = file.read()
my_line = ""
for line in read.splitlines():
if line == "DB_DATABASE=":
my_line = line
break
print my_line
Can someone please give me a little push here ?
Have a look at the config parser:
https://docs.python.org/3/library/configparser.html
It's more elegant than a self-made solution
Modify your .env to
[DB]
DB_HOST=http://localhost/
DB_DATABASE=bheng-local
DB_USERNAME=root
DB_PASSWORD=1234567890
UNIX_SOCKET=/tmp/mysql.sock
Python code
#!/usr/local/bin/python
import configparser
config = configparser.ConfigParser()
config.read('test.env')
print config.get('DB','DB_DATABASE')
Output:
bheng-local
Read https://docs.python.org/3/library/configparser.html
This should work for you
#!/usr/local/bin/python
file = open('test.env', "r")
read = file.read()
for line in read.splitlines():
if 'DB_DATABASE=' in line:
print line.split('=',1)[1]
#!/usr/local/bin/python
from configobj import ConfigObj
conf = ConfigObj('test.env')
print conf['DB_DATABASE']
from os import environ, path
from dotenv import load_dotenv
basedir = path.abspath(path.dirname(__file__))
load_dotenv(path.join(basedir, '.env'))
DB_DATABASE = environ.get('DB_DATABASE')
print(DB_DATABASE)
This could be another option

Is it possible to read a variable from a cfg file?

Is it possible to read paths from an external cfg (configuration) file.
I am making an application that opens a file. At present I have to copy and paste the path many times. I would like to write the path in my cfg file and call it from my Python program.
This my Python file :
import ConfigParser
import os
class Messaging(object):
def __init__(self):
self.config = ConfigParser.RawConfigParser()
self.rutaExterna = os.path.join(os.getcwd(), "app/properties.cfg")
self.config.read(['properties.cfg', self.rutaExterna])
def net(self):
# with open('/etc/network/interfaces', 'r+') as f:
direccion = self.config.read('direccion', 'enlace')
with open('direccion') as f:
for line in f:
found_network = line.find('network')
if found_network != -1:
network = line[found_network+len('network:'):]
print ('network: '), network
return network
CFG file :
[direccion]
enlace = '/etc/network/interfaces', 'r+'
I want to store the file path in a variable in my cfg file.
Then I can open that file using that variable in my Python file.
use self.config.get('direccion','enlace') instead of self.config.read('direccion', 'enlace') and then you can split() and strip() the strings and pass them as arguments to open():
import ConfigParser
import os
class Messaging(object):
def __init__(self):
self.config = ConfigParser.RawConfigParser()
self.rutaExterna = os.path.join(os.getcwd(), "app/properties.cfg")
self.config.read(['properties.cfg', self.rutaExterna])
def net(self):
direccion = self.config.get('direccion','enlace')
direccion = map(str.strip,direccion.split(','))
with open(*direccion) as f:
for line in f:
found_network = line.find('network')
if found_network != -1:
network = line[found_network+len('network:'):]
print ('network: '), network
return network
msg = Messaging()
msg.net()
also you don't need ' in your configuration file:
[direccion]
enlace = /etc/network/interfaces, r+
Tested this and it works.
config parser support reading directories.
some examples:
https://wiki.python.org/moin/ConfigParserExamples
updated CFG file (I've removed the 'r+' from your config file)
CFG file :
[direccion]
enlace = '/etc/network/interfaces'
updated Python code:
try:
from configparser import ConfigParser # python ver. < 3.0
except ImportError:
from ConfigParser import ConfigParser # ver. > 3.0
# instantiate
config = ConfigParser()
cfg_dir = config.get('direccion', 'enlace')
# Note: sometimes you might want to use os.path.join
cfg_dir = os.path.join(config.get('direccion', 'enlace'))

How do I load data from a text file in python?

I'm basically writing text to a file for example
data = ("save.data", "a+")
data.write(u"name = 'zrman'")
I wan't to be able to load that file and allow me to do this in python
print name
Any help would be great
-Thx
Use ConfigParser Python module. It's exactely what you're looking for.
Write :
import ConfigParser
config = ConfigParser.RawConfigParser()
config.set('main', 'name', 'zrman')
with open('conf.ini', 'wb') as configfile:
config.write(configfile)
Read :
from ConfigParser import ConfigParser
config = ConfigParser()
config.read('conf.ini')
print config.sections()
# ['main']
print config.items('main')
# [('name', 'zrman')]
Take a look at the docs here, this will walk you through the process of reading and writing files in python.
You could read in the lines and then exec the code:
f = open('workfile', 'w')
for line in f:
exec(line)
print name

Change value in ini file using ConfigParser Python

So, I have this settings.ini :
[SETTINGS]
value = 1
And this python script
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('settings.ini')
print parser.get('SETTINGS', 'value')
As you can see, I want to read and then replace the value "1" by another one. All I was able to do so far is to read it. I searched on the net how to replace it but I didn't find.
As from the examples of the documentation:
https://docs.python.org/2/library/configparser.html
parser.set('SETTINGS', 'value', '15')
# Writing our configuration file to 'example.ini'
with open('example.ini', 'wb') as configfile:
parser.write(configfile)
Python's official docs on configparser illustrate how to read, modify and write a config-file.
import configparser
config = configparser.ConfigParser()
config.read('settings.ini')
config.set('SETTINGS', 'value','15')
with open('settings.ini', 'w') as configfile:
config.write(configfile)
I had an issue with:with open
Other way:
import configparser
def set_value_in_property_file(file_path, section, key, value):
config = configparser.RawConfigParser()
config.read(file_path)
config.set(section,key,value)
cfgfile = open(file_path,'w')
config.write(cfgfile, space_around_delimiters=False) # use flag in case case you need to avoid white space.
cfgfile.close()
It can be used for modifying java properties file: file.properties
Below example will help change the value in the ini file:
PROJECT_HOME="/test/"
parser = ConfigParser()
parser.read("{}/conf/cdc_config.ini".format(PROJECT_HOME))
parser.set("default","project_home",str(PROJECT_HOME))
with open('{}/conf/cdc_config.ini'.format(PROJECT_HOME), 'w') as configfile:
parser.write(configfile)
[default]
project_home = /Mypath/

Categories

Resources