I want to set some paths of excel files in the INI file to be read by my code in Python. Can you please tell me how to call them?
In my ini
file I have something like this:
[common]
default_path = "C:/Users/XX/Desktop/Bk.xlsx/"
I want to set some paths of excel files in the INI file to be read by my code in Python. Can you please tell me how to call them?
In my ini
file I have something like this:
[common]
default_path = "C:/Users/XX/Desktop/Bk.xlsx/"
Command to install xlrd module : pip install xlrd
In config.ini dont need " so:
[general]
default_path = C:/Users/XX/Desktop/Bk.xlsx/
sample code:
import xlrd
import configparser
#Loading config
config = configparser.ConfigParser()
config.read("config.ini")
Excel_PATH = config["general"]["default_path"]
# Reading an excel file using Python
wb = xlrd.open_workbook(Excel_PATH)
sheet = wb.sheet_by_index(0)
# For row 0 and column 0
sheet.cell_value(0, 0)
As mentioned in the comment to your question, you can use the configparser module.
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
xlsx_path = config['common']['default_path']
Here is how to read and add your paths to your .INI file to the [common] section.
import configparser
config = configparser.ConfigParser()
config.read('yourfile.INI')
#set existing key-values in existing section
config.set('common', 'default_path', 'your_path_to_file.xls')
with open('yourfile.INI', 'w') as configfile:
config.write(configfile)
Let's say your config.ini
files has the following content.
[meta-properties]
server=localhost
port=8000
[db-properties]
name=student
password=1234
[logs]
level=warn
logdirectory=/var/logs/newapp/
This can be read by the following code. The file data is stored into dictionary format so that you can access each property of ini file by its key name.
import configparser
from pprint import pprint
def as_dict(config):
config_dict = {}
for section in config.sections():
config_dict[section] = {}
for key, val in config.items(section):
config_dict[section][key] = val
return config_dict
if __name__ == '__main__':
conf = configparser.ConfigParser()
conf.read(['config.ini'], encoding='utf-8')
pprint(as_dict(conf))
Gives output likes this
{
'db-properties': {
'name': 'student',
'password': '1234'
},
'logs': {
'level': 'warn',
'logdirectory': '/var/logs/newapp/'
},
'meta-properties': {
'port': '8000',
'server': 'localhost'
}
}```