Skip to main content
 首页 » 编程设计

python之是否可以从 cfg 文件中读取变量

2024年10月17日8qlqwjy

是否可以从外部 cfg(配置)文件中读取路径。

我正在制作一个打开文件的应用程序。目前我不得不多次复制和粘贴路径。我想在我的 cfg 文件中写入路径并从我的 Python 程序中调用它。

这是我的 Python 文件:

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文件:

[direccion] 
enlace = '/etc/network/interfaces', 'r+' 

我想将文件路径存储在我的 cfg 文件中的一个变量中。

然后我可以在我的 Python 文件中使用该变量打开该文件。

请您参考如下方法:

使用 self.config.get('direccion','enlace') 而不是 self.config.read('direccion', 'enlace') 然后您可以 split() 和 strip() 字符串并将它们作为参数传递给 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() 

您的配置文件中也不需要 ':

[direccion] 
enlace = /etc/network/interfaces, r+ 

测试了这个,它有效。