Rose
Rose

Reputation: 127

How do I add a linebreak at the end of a string in text files?

I tried doing this:

with open("contactbook.txt","a") as f:
     f.write("hello\n")

But it gets printed as:

'hello\n'

My code to read the file:

with open("contactbook.txt","r") as f:
     lines = sorted(f.readlines())
     print(lines)

EDIT:

I tried to check the text file and there \n really was interpreted as a linebreak!

But in python's shell it's still showing as \n

What am I doing wrong? Is it because of how I print it?

Upvotes: 0

Views: 58

Answers (2)

Rose
Rose

Reputation: 127

Just in case there are other people like me who gets the same problem...

The problem with my code before is the way I print it out so by changing how I read/print it to:

with open('contactbook.txt', 'r') as f:
     for lines in sorted(f):
          print(lines, end='')

It now works!

sabik's answer helped me realized this! :)

Upvotes: 0

Jiří Baum
Jiří Baum

Reputation: 6930

It's being written out fine.

The problem is that when you read the file back in, you print out the whole lines list in a single print(lines) statement; this will give you a form suitable for debugging, not really for display to the end-user, including writing out control characters as \n and so on.

If you check the file in any other way, you'll be able to confirm that it has the content that you want.

Upvotes: 2

Related Questions