I'm trying to print out strings that are read in from a regex
expression. For some of the lines of text being read in with my regex search, there is no data, so there isn't anything to read in. When this occur, I get the error, "AttributeError: 'NoneType' object has no attribute 'group'
. Could anyone help me write a work around in my code so that when nothing is read in from the regex search, the variable isn't printed out? I tried if (col3.group() != None):
, but that doesn't seem to work.
#!/usr/bin/env python
#purpose of script: To conduct an nslookup on a list of IP addresses
import os, csv, re
#get list of IP's from file
inFile='filesystem/Book1.txt'
ipList = []
with open(inFile, 'rb') as fi:
for line in fi:
line = line.replace(',', '')#remove commas and \n from list
line = line.replace('\r', '')
line = line.replace('\n', '')
ipList.append(line)# create list of IP addresses to lookup
#output results
outFile='filesystem/outFile.txt'
fo = open(outFile, 'w')
inc=0
writeToFileValue = ""
for e in ipList:
result = os.popen('nslookup ' + e).read()#send nsLookup command to cmd prompt
col1 = re.search(r'Server:.*', result, re.M|re.I)#use regex to extract data
col2 = re.search(r'Address: 8.8.8.8', result, re.M|re.I)
col3 = re.search(r'Name:.*', result, re.M|re.I)
col4 = re.search(r'Address: (?!8.8.8.8).*', result, re.M|re.I)
print col1.group()
print col2.group()
if (col3.group() != None):
print col3.group() # if none, skip
if (col4.group() != None):
print col4.group() # if none, skip
instead of this:
if (col3.group() != None):
print col3.group() # if none, skip
do this:
try col3.group():
print col3.group()
except AttributeError:
pass