Line break in a .txt file

0

How to break the line when passing my data to a .txt file?

The code I'm using to open, write, and close .txt are these:

arquivo = open("arquivo.txt", "a", newline="")
arquivo.write("%s;" % nome_critico)
arquivo.close()

What I'm wanting is for all data to look this way:

Andnotlikethis:

Myfullcodeisdown: link

    
asked by anonymous 03.08.2017 / 02:49

1 answer

0

Use line break with the appropriate escape for this, just add '\n' to the end of the string. In the example below I read the strings from a list and add the line break when I write to the file:

arquivo = open("arquivo.txt", "a", newline="")
persons = ['Jose antonio de oliveira; [email protected]', 
           'Ana Fake da Silva; [email protected]']

for p in persons:
    arquivo.write(p+'\n')
arquivo.close()

Displaying the contents of the file with the command cat (Linux):

cat arquivo.txt
Jose antonio de oliveira; [email protected]
Ana Fake da Silva; [email protected]
  

Edited
  After reading the comments more closely, I thought I should complement the answer.

Reading the file:

With readlines() :

lines = open('arquivo.txt','r').readlines()
print (lines) 
['Jose antonio de oliveira; [email protected]\n', 'Ana Fake da Silva; [email protected]\n']

With splitlines() :

lines = open('arquivo.txt','r').read().splitlines()
print (lines)
['Jose antonio de oliveira; [email protected]', 'Ana Fake da Silva; [email protected]']     

See that splitlines() , "automagically" removes the escape for line break.

    
03.08.2017 / 06:27