Reputation: 2552
I am getting an error from this Python code:
with open('names') as f:
names = f.read()
names = names.split('\n')
names.pop(len(names) - 1)
names = shuffle(names)
f.close()
assert len(names) > 100
Error:
Python: TypeError: object of type 'NoneType' has no len()
The assert statement is throwing this error, what am I doing wrong?
Upvotes: 19
Views: 185353
Reputation: 11
I was faces this issue but after change object into str, problem solved. str(fname).isalpha():
Upvotes: 0
Reputation: 143037
What is the purpose of this
names = list;
? Also, no ;
required in Python.
Do you want
names = []
or
names = list()
at the start of your program instead? Though given your particular code, there's no need for this statement to create this names
variable since you do so later when you read data into it from your file.
@JBernardo has already pointed out the other (and more major) problem with the code.
Upvotes: 3
Reputation: 304137
You don't need to assign names
to list
or []
or anything else until you wish to use it.
It's neater to use a list comprehension to make the list of names.
shuffle
modifies the list you pass to it. It always returns None
If you are using a context manager (with ...
) you don't need to close the file explicitly
from random import shuffle
with open('names') as f:
names = [name.rstrip() for name in f if not name.isspace()]
shuffle(names)
assert len(names) > 100
Upvotes: 5
Reputation: 33387
shuffle(names)
is an in-place operation. Drop the assignment.
This function returns None
and that's why you have the error:
TypeError: object of type 'NoneType' has no len()
Upvotes: 28