Reputation: 1
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)
Upvotes: 0
Views: 46
Reputation: 8921
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")
Upvotes: 2