0

I am trying to call a function- write_corpus_to_file, however when I run the program I get the error code 'Attribute error: List has no attribute 'txt''. I am a python beginner, can anyone help?

THE FUNCTION:

def write_corpus_to_file(mycorpus, myfile):
    f = open(myfile, 'w')
    newcorpus = ''.join(mycorpus)
    f.write(newcorpus)
    f.close()                

SECTION OF THE MAIN LOOP:

elif user_input=="a":
    addseq = input("Enter new input to corpus ")
    tidy_text(addseq)
    extcorpus = corpus.extend(addseq)
    write_corpus_to_file(extcorpus, corpus.txt)
1
  • 1
    myfile should be a string, not a variable name. So corpus.txt should really be "corpus.txt" Commented Nov 18, 2017 at 9:08

1 Answer 1

2

You forgot to put the filename in quotes:

write_corpus_to_file(extcorpus, "corpus.txt")

If you don't have quotes, then python takes corpus.txt literally, and attempts to access the txt attribute of the variable called corpus. That of course doesn't exist, hence the error.

Also, a recommendation. Instead of this:

f = open(myfile, 'w')
f.write(newcorpus)
f.close() 

Do this:

with open(myfile, 'w') as f:
    f.write(newcorpus)

This method ensures that resources are properly released, and that the file is written to and closed properly even in case of an error.

EDIT: extend, like other functions that operate on lists, works in-place. This means that it modifies the list, and does not return a new one. Therefore when you do extcorpus = corpus.extend(addseq), extcorpus is given no value, since extend doesn't return anything.

Change your code like so:

elif user_input=="a":
    addseq = input("Enter new input to corpus ")
    tidy_text(addseq)
    corpus.extend(addseq)
    write_corpus_to_file(corpus, "corpus.txt")
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! When I do this however I am getting another error code: TypeError: Can only join an iterable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.