Write a string list in a file

0

I have a list and I wanted to write to another file

["AMANDA,"JULIANA","VANESSA","PATRICIA"]

In a document using Python, I did however the file get all together type like this:

AMANDAJULIANAVANESSAPATRICIA

How could I fix this?

def ordem_txt(palavras):  
       arq = open(palavras, 'r')  
       texto = arq.read()  
       palavras = texto.replace("\n", " ").split(" ")  
       palavras.sort(reverse=False)  
       #print(palavras)  
       return palavras  

def write_txt(palavras, caminho):  
    arq = open(caminho, "w")  
    arq.writelines(palavras)  
    arq.close()  
    
asked by anonymous 24.05.2018 / 16:55

1 answer

1

As commented, the writelines function does not add any separator between list values, so if you would like to write one word per line, you need to manually add the \n character. For example:

arq.writelines(palavra + '\n' for palavra in palavras)

Or use only the write function by adding line breaks with join :

arq.write('\n'.join(palavras))

Official documentation of writelines :

  

writelines (lines) : Write a list of lines to the stream. Line separators   are not added , so it is usual for each of the lines provided to have a   line separator at the end.

    
24.05.2018 / 17:55