Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending line to a existing file having extra new line in Python

Tags:

python

I have a text file

apple
banana

Now you watch closely there is blank line at the end.

When in do append

f = open("file.txt",'a')
f.write("orange")
f.close()

I get output:

apple
banana

orange

I want to remove the blank line in between during appends.

I know i can do that manually going to the file and removing the extra new line. But i want to do it in python. So every time the blank line is there its gets removed automatically like this:

apple
banana
orange

I search and experimented but no avail

like image 972
vipulb Avatar asked Jun 28 '12 13:06

vipulb


3 Answers

use:

f = open("file.txt",'ab')

'ab' instead of only 'a'

like image 200
Ronny Avatar answered Dec 11 '22 09:12

Ronny


You can't, because, well, append mode does exactly that: It appends. To the newline. You will have to read in the file, remove the newline at the end, write it out and then append.

Or, open the file for reading and writing (mode 'r+'), seek to the end, remove the newline, and then continue with writing.

I think this could do the trick:

f = open('file.txt', 'r+')
f.seek(-2, 2) # last character in file
if f.read(2) == '\n\n':
   f.seek(-1, 1) # wow, we really did find a newline! rewind again!
f.write('orange')
f.close()
like image 42
Daren Thomas Avatar answered Dec 11 '22 10:12

Daren Thomas


A simple solution is to overwrite the whole file instead of modifying it in place:

with open("file.txt") as input:
    # Read non-empty lines from input file
    lines = [line for line in input if line.strip()]
with open("file.txt", "w") as output:
    for line in lines:
        output.write(line)
    output.write("orange\n")

This code will work fine as long as the file is not too large.

You could do this more efficiently by opening the file for reading and writing, finding the number of newline characters at the end of the file, seeking to the position after the first trailing newline character and writing the line to append there. This is more efficient, but also requires more elaborate code, so I'd only do this if the simple solution isn't fast enough.

Edit: Here's my take on the more efficient way of doing this:

with open("file.txt", "r+U") as f:
    try:
        f.seek(-1, 2)
        while f.read(1) == "\n":
            f.seek(-2, 1)      # go back two characters, since
                               # reading advances by one character
    except IOError:            # seek failed, so the file consists
        f.seek(0)              # exclusively of newline characters
    else:
        f.write("\n")          # Add exactly one newline character
    f.write("orange\n")        # Add a new line

This works correctly for any number of trailing newline characters, including none at all or more than two.

like image 24
Sven Marnach Avatar answered Dec 11 '22 10:12

Sven Marnach