Importing file data into a list from a function

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; -   data    info    hosta -   data    info    hostb -   data    info    hostc -   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;

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 =

#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

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 return
to return the result to the caller.

def importlines():
    with open('C:/scripts/nagios/filename.txt') as mf:
        return [l.split()[0] for l in mf]

would return only
a list of ip addresses. You can assign the result directly to hosts

hosts = importlines()

Your own code did not return anything in importlines()
, and the default return values for a python function is None

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Importing file data into a list from a function

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录