gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:11 25 4
gpt4 key购买 nike

是否可以从外部 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+

测试了这个,它有效。

关于python - 是否可以从 cfg 文件中读取变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40326433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com