Python: TypeError: object of type 'NoneType' has no len()

前端 未结 4 1241
-上瘾入骨i
-上瘾入骨i 2021-02-14 15:56

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)
    n         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-14 16:54

    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
    

提交回复
热议问题