Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Python I/O using random library, keep getting errors trying to use .choice (anyone?)

I've been trying to practice what I learned from the Python course and the Python I/O workshop. I'm trying to take a list of words in a text file and choose 7 random words and add them to another file while checking that file to see if a word has already been added.

import random

words = []
# open up list of words
def new_words(n):
    with open('word_list.txt') as file:
        i = 0
        while i < n:
            rand = random.choice(file.readlines)
            words.append(rand)
            i += 1

def check_duplicates(words):
    with open('added.txt') as file:
        i = 0
        for word in words:
            if word in file.readlines:
                words.remove(word)
                i += 1
        new_words(i)

def add_to_file(words):
    with open('added.txt' 'a') as file:
        file.writelines(words)

new_words(7)
check_duplicates(words)
add_to_file(words)
word_list.txt:

cat
dog
cheddar
love
cheese
usb
paper
table
sleep
tired
lamp
pencil
pen
lead
added.txt:

cat

But I keep getting this error, I don't understand it and have tried searching online and docs to no avail:

Traceback (most recent call last):
  File ".../word_list.py", line 54, in <module>
    new_words(7)
  File ".../word_list.py", line 37, in new_words
    rand = random.choice(file.readlines)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/random.py", line 253, in choice
    i = self._randbelow(len(seq))
TypeError: object of type 'builtin_function_or_method' has no len()

Can anyone explain what I'm doing wrong and what this error is?

I am having the same issue. Did you get a solution for this?

No seems like this question is either under the radar or people aren't interested in answering. Shame :(

1 Answer

Maybe I 'm wrong but I think you have to put a comma between the file and the "mode" inside of the "add_to_file()" function:

def add_to_file(words):
    with open('added.txt', 'a') as file:
        file.writelines(words)

I added that but makes no difference to the error, good spot though thanks!