"must be str, not list" error when writing to file

1

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

What I've done so far is 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're giving this error:

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 this section to see if you can tell me why the error.

    
asked by anonymous 08.03.2016 / 23:04

1 answer

2

There are several things wrong here. Starting with:

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

You are opening the file in read-only mode. That is, it will not write further in your code, which seems to be the intention. You need to switch 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. No need to do that. It is simpler to just write at the end of it, and not read everything and then write.

Once you've done this, to write to the file, just call writeline or writelines , as you were already doing.

close does not need within with .

About this error:

  

TypeError: must be str, not list

The error is clear. You are moving to writelines a list. The function asks string . If the intention is to write a list of string s in the file, the following construct is more appropriate:

for linha in f1:
    arqParcial.writeline(linha)
    
08.03.2016 / 23:15