簡體   English   中英

從文本文件 python 中提取並獲取值

[英]Extract and get value from a text file python

我已經使用 paramiko 庫在遠程機器上執行了 ssh 命令,並將輸出寫入文本文件。 現在,我想從文本文件中提取幾個值。 文本文件的輸出如下所示

b'\nMS Administrator\n(C) Copyright 2006-2016 LP\n\n[MODE]> SHOW INFO\n\n\nMode: \nTrusted Certificates\n1 Details\n------------\n\tDeveloper ID: MS-00c1\n\tTester ID: ms-00B1\n\tValid from: 2030-01-29T06:51:15Z\n\tValid until: 2030-01-30T06:51:15Z\n\t

我如何獲得開發人員 ID 和測試人員 ID 的值。 文件很大。

根據用戶的建議,我寫了下面的代碼片段。

file = open("Output.txt").readlines()
for lines in file:
    word = re.findall('Developer\sID:\s(.*)\n', lines)[0]
    print(word)

如果我刪除索引,我會看到錯誤 IndexError: list index out of range。 我看到空輸出

file = open("Output.txt").readlines()
developer_id=""

for lines in file:
    if 'Developer ID' in line:                                                                                         
        developer_id = line.split(":")[-1].strip()                                                                     

print developer_id

您可以使用正則表達式

text = """\nMS Administrator\n(C) Copyright 2006-2016 LP\n\n[MODE]> SHOW INFO\n\n\nMode: \nTrusted Certificates\n1 Details\n------------\n\tDeveloper ID: MS-00c1\n\tTester ID: ms-00B1\n\tValid from: 2030-01-29T06:51:15Z\n\tValid until: 2030-01-30T06:51:15Z\n\t"""
import re
developerID = re.match("Developer ID:(.+)\\n", text).group(0)
testerID = re.match("Tester ID:(.+)\\n", text).group(0)

如果您的輸出格式一致,您可以使用像 line.split() 這樣簡單的方法:

developer_id = line.split('\n')[11].lstrip()
tester_id = line.split('\n')[12].lstrip()

同樣,這假設每一行都使用相同的格式。 否則,請按照上面的建議使用正則表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM