0

Please help. It's really children's question but I'm at a loss. Why I can't to return array?

There is my script :

groups=[]

host_groups_list = '/usr/local/host_groups.list'

def read_file(file_path):
        open_file = open(host_groups_list, "r+")
        list=[]
        for i in open_file:
                list.append(str(i.replace("\n", "")))
        print list
        return list

goups = read_file(host_groups_list)
print groups

Output :

['hostgroup1', 'hostgroup2']
[]
1
  • 1. You didn't close that file after you open it. 2. A typo and use list as variable name as Mike said. 3. list.append(str(i.replace("\n", ""))), str() is useless here. 4. I think you mean open_file = open(file_path, "r+") instead of open_file = open(host_groups_list, "r+"). 5. groups = with open(''/usr/local/host_groups.list'') as f: [i.strip() for i in f]. Commented Dec 6, 2015 at 3:53

1 Answer 1

3

Spelling is important:

goups = read_file(host_groups_list)
print groups

Note the missing r in goups.

You don't need the groups=[] in the beginning. Delete it and Python will give a name error for your print statement.

Better don't use list as a name for your variables because it shadows a built-in.

Sign up to request clarification or add additional context in comments.

1 Comment

@JustMe: use editor with auto-completion (I personally recommend Sublime Text 2) to avoid mistakes like this in future. And, don't create unneeded globals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.