I have a requirement to create repeating config files using the IP and hostnames of some servers. This data is contained in a large list similar to the mock data included;
192.168.0.1 - data info hosta 192.168.0.2 - data info hostb 192.168.0.3 - data info hostc 192.168.0.4 - data info hostb
This data contains arbitrary information that I don’t want, such as the following items, ‘
- data info '
I had the idea that I could read the split data into a list. Then I would be able to loop over the list specifying only each numbered element within the list to be displayed, leaving only;
192.168.0.1 192.168.0.2 ...
This would then be placed into a new list containing only the IP addresses.
I created a function that would read the the file into a list
def importlines(): mf = open('C:\scripts\nagios\filename.txt','r') lines = mf.read().split() print(lines) mf.close() #the data is read in correctly #I then attempted to create a blank list hosts =  #then append the output from the function call to the list hosts.append(importlines())
However this results in ‘None’, if I execute hosts.append(importlines()) once again I’m met with None,None. So it’s it seems to be appending an elememt containing nothing into the list. I’ve tried executing hosts.append(print(importlines())) however I have the same issue.
As you can tell I’m what you might describe as an accidental sysadmin and have no experience in this. I’m also aware of the issue that this will create one large list, in my head I believe I require a list containing a list of each line. Am I off the mark here?
You are splitting the whole file, not each line. Moreover, your function only prints
, it doesn’t actually use
to return the result to the caller.
def importlines(): with open('C:/scripts/nagios/filename.txt') as mf: return [l.split() for l in mf]
would return only
a list of ip addresses. You can assign the result directly to
hosts = importlines()
Your own code did not return anything in
, and the default return values for a python function is