读取文件并解析数据

时间:2018-07-27 17:06:53

标签: python-3.5

我正在读取文件并仅打印行中具有“ load”且正在运行的行,但是我希望数据更加清晰或清晰,因为输出数据为[soi-aahh] out: 16:45:50 up 436 days, 2:06, 5 users, load average: 0.08, 0.02, 0.00,其中包含主机名在out之后的括号内,我要删除该括号,并希望将数据查找为两列格式,或者至少将它们删除:

$ cat logs.py
#!/python/v3.6.1/bin/python3
with open("file_1") as f:
    data = f.read()
    for line in data.splitlines():
        if "load" in line:
            print(line)
            print("")

文件内容

$ cat file_1
[soi-aahh] sudo: uptime
[soi-aahh] out: sudo password:
[soi-aahh] out:  16:45:50 up 436 days,  2:06,  5 users,  load average: 0.08, 0.02, 0.00
[soi-aahh] out:

[soi-aabk] sudo: uptime
[soi-aabk] out: sudo password:
[soi-aabk] out:  16:45:50 up 586 days, 23:08,  7 users,  load average: 1.01, 1.03, 1.00
[soi-aabk] out:

[soi-abrrj] sudo: uptime
[soi-abrrj] out: sudo password:
[soi-abrrj] out:  16:45:50 up 219 days,  6:31,  4 users,  load average: 0.00, 0.00, 0.00
[soi-abrrj] out:

[soi-ritsh] sudo: uptime
[soi-ritsh] out: sudo password:
[soi-ritsh] out:  16:45:50 up 586 days, 23:13, 15 users,  load average: 5.01, 5.02, 5.04
    [soi-ritsh] out:

脚本输出:

$ ./logs.py
[soi-aahh] out:  16:45:50 up 436 days,  2:06,  5 users,  load average: 0.08, 0.02, 0.00

[soi-aabk] out:  16:45:50 up 586 days, 23:08,  7 users,  load average: 1.01, 1.03, 1.00

[soi-abrrj] out:  16:45:50 up 219 days,  6:31,  4 users,  load average: 0.00, 0.00, 0.00

[soi-ritsh] out:  16:45:50 up 586 days, 23:13, 15 users,  load average: 5.01, 5.02, 5.04

所需:

Hostname        Uptime
soi-aahh        16:45:50 up 436 days

或至少低于以下水平:

soi-aahh: 16:45:50 up 436 days, 2:06, 5 users, load average: 0.08, 0.02, 0.00

请建议是否有更好的方法来读取文件并执行此操作。

1 个答案:

答案 0 :(得分:1)

您可能要修剪线条:

with open("file_1") as f:
    data = f.read()
    print('Hostname \t Uptime')
    for line in data.splitlines():
        if "load" in line:
            print(line.replace('] out: ', '\t').strip('['))
            print("")