Error "must be str, not list" while writing to file

Asked

Viewed 785 times

1

I have a job to do but I can’t find the error. This excerpt from the program needs to add words in a text file cumulatively. That is, every time you go through the loop will add numbers and words in the text file without deleting what is already written.

What I’ve done so far is like this:

arqParcial=open("parcial.txt","r")
texto=arqParcial.readline()
f1=[]
for i in range (len(texto)):
            palavra=texto[i].split()
            f1.append(palavra)
print(f1)
arqParcial.writelines(f1)
arqParcial.close()

But you keep making that mistake:

Traceback (most recent call last):
  File "C:/Python34/teste3.py", line 8, in <module>
    arqParcial.writelines(f1)
TypeError: must be str, not list

I have no idea why.

The program is much longer. I just put in this excerpt to see if you can tell me why the mistake.

1 answer

2

There are a lot of things wrong here. Starting with:

arqParcial=open("parcial.txt","r")

You are opening the file in read-only mode. That is, you will not write further in your code, which seems to be the intention. It is necessary to change to:

with open("parcial.txt", "a") as arqParcial:
    ...

Everything else you wrote seems to be of no use because apparently you were reading to write again in the file. You don’t have to do that. It’s simpler just to write at the end of it, and not to read everything and then write.

That done, to write to the file, just call writeline or writelines, as you were already doing.

The close don’t need inside the with.

About this mistake:

Typeerror: must be str, not list

The error is clear. You are passing to writelines a list. The function asks string. If the intention is to write a list of strings, the following construction is more appropriate:

for linha in f1:
    arqParcial.writeline(linha)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.