2017-06-22 57 views
-1

我新手到Python和我試圖找到文件中的字和打印「整個」匹配線搜索文件和打印匹配的行一個字 - Python的

的exmaple.txt有以下文字:

sh version 

Cisco IOS Software, 2800 Software (C2800NM-IPBASE-M), Version 12.4(3h), RELEASE SOFTWARE (fc2) 

sh inventory 

NAME: "2811 chassis", DESCR: "2811 chassis, Hw Serial#: FHK1143F0WY, Hw 
NAME: "High Speed Wan Interface card with 16 RS232 async ports(HWIC-16A)", 
NAME: "High Speed Wan Interface card with 16 RS232 async ports(HWIC-16A)", 
NAME: "16 Port 10BaseT/100BaseTX EtherSwitch" 

要求: 要查找的字符串「Cisco IOS軟件」,如果發現打印的是整條生產線。 查找 「姓名:」 在文件中,如果發現打印的是整條生產線&數出現的次數

代碼:

import re 
def image(): 
    file = open(r'C:\Users\myname\Desktop\Python\10_126_93_132.log', 'r') 
    for line in file: 
     if re.findall('Cisco IOS Software', line) in line: 
      print(line) 
     else: 
      print('Not able to find the IOS Information information') 

def module(): 
    file = open(r'C:\Users\myname\Desktop\Python\10_126_93_132017.log', 'r') 
    for line in file: 
     if re.findall('NAME:') in line: 
      print(line) 
     else: 
      print('No line cards found') 

錯誤:

Traceback (most recent call last): 
File "C:/Users/myname/Desktop/Python/copied.py", line 19, in <module>image() 
File "C:/Users/myname/Desktop/Python/copied.py", line 5, in image if re.findall('Cisco IOS Software', line) in line: 
TypeError: 'in <string>' requires string as left operand, not list 
+0

're.findall()'返回一個列表。您只能使用'如果在線' – kuro

回答

0

簡單的方法:

with open('yourlogfile', 'r') as fp: 
    lines = fp.read().splitlines() 
    c = 0 
    for l in lines: 
     if 'Cisco IOS Software' in l or 'NAME:' in l: 
      print(l) 
     if 'NAME:' in l: c += 1 
    print('\nNAME\'s count: ', c) 

輸出:

Cisco IOS Software, 2800 Software (C2800NM-IPBASE-M), Version 12.4(3h), RELEASE SOFTWARE (fc2) 
NAME: "2811 chassis", DESCR: "2811 chassis, Hw Serial#: FHK1143F0WY, Hw 
NAME: "High Speed Wan Interface card with 16 RS232 async ports(HWIC-16A)", 
NAME: "High Speed Wan Interface card with 16 RS232 async ports(HWIC-16A)", 
NAME: "16 Port 10BaseT/100BaseTX EtherSwitch" 

NAME's count: 4 
+0

感謝您的回覆:) – Vadiraj

1

也許這就是你要找的內容:

with open('some_file', 'r') as f: 
    lines = f.readlines() 
    for line in lines: 
     if re.search(r'some_pattern', line): 
      print line 
      break 

BTW:你提的問題是非常不可讀。在按提問問題按鈕之前,您應該檢查如何正確發佈問題。

+0

當然,謝謝,將檢查:) – Vadiraj

相關問題