Reputation: 171
I am trying to chose a random number from the hostnumbers.txt
file.
I am getting this error:
TypeError: object of type 'function' has no len()
while running this code:
def prev_hosting_comp_random():
with open('hostnumbers.txt') as hosts:
read_hosts = csv.reader(hosts, delimiter = '\n')
read_hosts = [int(x[0]) for x in list(read_hosts) if x]
return random.choice(prev_hosting_comp_random)
print(type(prev_hosting_comp_random()))
and the hostnumbers.txt file looks like this:
2312
2324
234234
1245
234
Can you please help me fix this?
EDIT: ERROR TRACEBACK
Traceback (most recent call last):
File "codeOffshoreupdated.py", line 94, in <module>
'previous_hosting_id': prev_hosting_comp_random(),
File "codeOffshoreupdated.py", line 20, in prev_hosting_comp_random
return random.choice(prev_hosting_comp_random)
File "/usr/lib64/python3.7/random.py", line 259, in choice
i = self._randbelow(len(seq))
TypeError: object of type 'function' has no len()
Upvotes: 0
Views: 2061
Reputation: 1841
return random.choice(prev_hosting_comp_random)
seems wrong, as it is indeed a function as the error message said. You probably want to replace it by
return random.choice(read_hosts)
Upvotes: 1
Reputation: 643
I think you meant
def prev_hosting_comp_random():
with open('file.txt') as hosts:
read_hosts = csv.reader(hosts, delimiter = '\n')
read_hosts = [int(x[0]) for x in list(read_hosts) if x]
return random.choice(read_hosts)
because random.choice(prev_hosting_comp_random)
wont work because prev_hosting_comp_random
is a function
Upvotes: 1