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/
Related
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')
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
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
I'm using the Python module iniparse to save keys to an INI file, but I was wondering if there is a way to delete keys and sections from the INI file using iniparse. I know it's possible using ConfigParser and that iniparse is backwards compatible with ConfigParser, but I can't figure out how to perform the deletions using the same iniparse object.
from iniparse import INIConfig, RawConfigParser
cfg = INIConfig(open('options.ini'))
print cfg.section.option
cfg.section.option = 'new option'
# Maybe I need to use RawConfigParser somehow?
cfg.remove_option('section','option')
cfg.remove_section('section')
f = open('options.ini', 'w')
print >>f, cfg
f.close()
To remove a section or an option you simply need to delete it. Your revised code would be:
from iniparse import INIConfig
cfg = INIConfig(open('options.ini'))
print cfg.section.option
cfg.section.option = 'new option'
del cfg.section.option
del cfg.section
f = open('options.ini', 'w')
print >>f, cfg
f.close()
Note that if you want to delete a whole section you don't need to delete its options before: just delete the section.
Note also that this way of doing it feels more Pythonic than using remove_option and remove_section methods.
I need to search for a certain parameter known as jvm_args in a configuration file known as config.ini
**contents of config.ini:
first_paramter=some_value1
second_parameter=some_value2
jvm_args=some_value3**
I need to know how to find this parameter in my file and append something to its value, (i.e append a string to the string some_value3).
If you "just" want to find keys and values in an ini file, I think the configparser module is a better bet than using regexps. The configparser asserts that the file has "sections", though.
Documentation for configparser is here: http://docs.python.org/library/configparser.html - useful examples at the bottom. The configparser can also be used for setting values and writing out a new .ini-file.
Input file:
$ cat /tmp/foo.ini
[some_section]
first_paramter = some_value1
second_parameter = some_value2
jvm_args = some_value3
Code:
#!/usr/bin/python3
import configparser
config = configparser.ConfigParser()
config.read("/tmp/foo.ini")
jvm_args = config.get('some_section', 'jvm_args')
print("jvm_args was: %s" % jvm_args)
config.set('some_section', 'jvm_args', jvm_args + ' some_value4')
with open("/tmp/foo.ini", "w") as fp:
config.write(fp)
Output file:
$ cat /tmp/foo.ini
[some_section]
first_paramter = some_value1
second_parameter = some_value2
jvm_args = some_value3 some_value4
You can use re.sub
import re
import os
file = open('config.ini')
new_file = open('new_config.ini', 'w')
for line in file:
new_file.write(re.sub(r'(jvm_args)\s*=\s*(\w+)', r'\1=\2hello', line))
file.close()
new_file.close()
os.remove('config.ini')
os.rename('new_config.ini', 'config.ini')
also check ConfigParser
As both avasal and tobixen have suggested, you can use the python ConfigParser module to do this. For example, I took this "config.ini" file:
[section]
framter = some_value1
second_parameter = some_value2
jvm_args = some_value3**
and ran this python script:
import ConfigParser
p = ConfigParser.ConfigParser()
p.read("config.ini")
p.set("section", "jvm_args", p.get("section", "jvm_args") + "stuff")
with open("config.ini", "w") as f:
p.write(f)
and the contents of the "config.ini" file after running the script was:
[section]
framter = some_value1
second_parameter = some_value2
jvm_args = some_value3**stuff
without regex you can try:
with open('data1.txt','r') as f:
x,replace=f.read(),'new_entry'
ind=x.index('jvm_args=')+len('jvm_args=')
end=x.find('\n',ind) if x.find('\n',ind)!=-1 else x.rfind('',ind)
x=x.replace(x[ind:end],replace)
with open('data1.txt','w') as f:
f.write(x)