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 Answer 1
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
Mike Müller
86.1k21 gold badges174 silver badges165 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
GingerPlusPlus
@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.
lang-py
listas variable name as Mike said. 3.list.append(str(i.replace("\n", ""))),str()is useless here. 4. I think you meanopen_file = open(file_path, "r+")instead ofopen_file = open(host_groups_list, "r+"). 5.groups = with open(''/usr/local/host_groups.list'') as f: [i.strip() for i in f].