1

So I have a file that is in this format (no, this is not what the file looks exactly like)

aaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbb
ccccccccccccccccccc
ddddddddddddddddddd

I want to append a new line to the file so that it looks like

aaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbb
ccccccccccccccccccc
ddddddddddddddddddd
eeeeeeeeeeeeeeeeeee

but whenever I use

with open(filename, "a") as updatedFile:
    nextLine="\n%s" % (lineToAdd)
    updatedFile.write(nextLine)

I get

aaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbb
ccccccccccccccccccc
ddddddddddddddddddd

eeeeeeeeeeeeeeeeeee

How would I go about fixing this?

2
  • 1
    Are you using windows? Try \r\n Commented Dec 4, 2013 at 23:17
  • No, I am on UNIX so \r doesn't work Commented Dec 4, 2013 at 23:18

1 Answer 1

5

You have a file that already had a newline at the end:

aaaaaaaaaaaaaaaaaaa\n
bbbbbbbbbbbbbbbbbbb\n
ccccccccccccccccccc\n
ddddddddddddddddddd\n

and you wrote a newline plus the additional line:

aaaaaaaaaaaaaaaaaaa\n
bbbbbbbbbbbbbbbbbbb\n
ccccccccccccccccccc\n
ddddddddddddddddddd\n
\n
eeeeeeeeeeeeeeeeeee

Write your additional line with the newline at the end:

with open(filename, "a") as updatedFile:
    nextLine="%s\n" % (lineToAdd)
    updatedFile.write(nextLine)

so that you end up with:

aaaaaaaaaaaaaaaaaaa\n
bbbbbbbbbbbbbbbbbbb\n
ccccccccccccccccccc\n
ddddddddddddddddddd\n
eeeeeeeeeeeeeeeeeee\n
Sign up to request clarification or add additional context in comments.

1 Comment

Ah I see the logic now. Thanks so much for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.