从python文件中读取一行

2024-10-01 11:33:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为mcelog.conf的文件,我正在我的代码中读取这个文件。文件的内容是

no-syslog = yes   # (or no to disable)
logfile = /tmp/logfile

程序将读取mcelog.conf文件并检查no-syslog标记,如果no-syslog = yes,则程序必须检查标记logfile,并将读取logfile标记。{cd7>让任何人知道如何得到这个值

^{pr2}$

Tags: or文件tono代码标记程序内容
3条回答

我喜欢configparser模块的建议,下面是一个例子(python3)

对于给定的输入,它将输出reading /var/log/messages

import configparser, itertools
config = configparser.ConfigParser()
filename = "/tmp/mcelog.conf"

def readLogFile(filename):
    if filename:
        print("reading", filename)
    else:
        raise ValueError("unable to read file")

section = 'global'
with open(filename) as fp:
    config.read_file(itertools.chain(['[{}]'.format(section)], fp), source = filename)

no_syslog = config[section]['no-syslog']
if no_syslog == 'yes':
    logfile = "/var/log/messages"
elif no_syslog == 'no':
    logfile = config[section]['logfile']

if logfile:
    mcelogPathFound = True

memoryErrors = readLogFile(logfile)

将代码更改为:

with open('/etc/mcelog/mcelog.conf', 'r+') as fp:
    for line in fp:
        if re.search("no-syslog =", line) and re.search("= no", line):
            memoryErrors = readLogFile("/var/log/messages")
            mcelogPathFound = true
            break
        elif re.search("no-syslog =", line) and re.search("= yes", line):
            continue
        elif re.search("logfile =", line):  
            emoryErrors = readLogFile(line.split("=")[1].strip())   # Here I want to pass the value "/tmp/logfile" but currently "logfile = /tmp/logfile" is getting passed
            mcelogPathFound = true
            break
 fp.close()

这是因为你只想读这行的一部分,而不是整个内容,所以我就用“=”号把它分开,然后去掉空白

只需拆分行即可获得所需的值:

line.split(' = ')[1]

但是,您可能需要查看configparser module的文档。在

相关问题 更多 >