Write a string list to a file

Asked

Viewed 974 times

0

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

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

In a document using Python, I managed however the file gets all together 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()  
  • Put your code in the question, please.

  • arq.writelines() does not add line separators, you have to add them to the list items yourself.

1 answer

1


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

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

Or just use the function write adding line breaks with the join:

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

Official documentation of writelines:

writelines(): 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.

Browser other questions tagged

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