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']
[]
asked Dec 5, 2015 at 14:58
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.

Remi Guan
22.5k17 gold badges68 silver badges90 bronze badges
answered Dec 5, 2015 at 15:00
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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.