pythonbegineer pythonbegineer - 1 month ago 12
Python Question

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.

Answer

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.