Line break in a file . txt

Asked

Viewed 9,332 times

1

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

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 hoping is that all the data will stay that way:

And not like this:

My complete code is down: https://repl.it/Jbl1/0

  • At the last printed value, you can not put %s\n?

  • The problem with doing this is that n goes along with the .txt. file ex: "Max;6,000; n"

  • That’s how it worked for me: https://repl.it/Jbl1/3. Basically I put the file.write("\n") at the end of if.

  • 1

    @Kennethanderson, you take that easy \n' with rstrip, example: 'test string\n'.rstrip()

  • 1

    Or you can use splitlines() to remove line breaks, when you read the file. See in the answer editing.

1 answer

1


Use line break with the appropriate exhaust for this, just add '\n' at 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()

Showing the file contents 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 carefully, 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(), removes "automatic" the exhaust for line breaking.

Browser other questions tagged

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