Search code examples
pythoncsvreadlines

How can I delete "\n" lines from a file in Python?


I need to check if the .csv file I'm working with ends with more than 1 "\n" line. If it finds more than a blank line, it removes them all but one.

My code is:

import os
from pathlib import Path


def remove_blanks():
    dirname = os.path.dirname(os.path.abspath(__file__))
    path: Path = Path(os.path.join(dirname, "data.csv"))
    with open(path, "r+") as op:
        lines = op.readlines()
        for line in lines:
            if line == "\n":
                op.write(line.rstrip("\n"))

The .csv file is something like ['01-01-2019,0,0,0\n', '18-05-2019,33,31,48\n', '\n', '\n', '\n'] and the output I'd want is ['01-01-2019,0,0,0\n', '18-05-2019,33,31,48\n', '\n'] but it doesn't seem to be able to delete any line.


Solution

  • I managed to work this out, with this code:

    import os
    from pathlib import Path
    
    
    def remove_blanks():
        dirname = os.path.dirname(os.path.abspath(__file__))
        path: Path = Path(os.path.join(dirname, "data.csv"))
        with open(path, "r") as op:
            lines = op.readlines()  # read lines in memory
        with open(path, "w") as op: # re-write everything from the beginning
            for line in lines:
                if line != "\n":
                    op.write(line)
                else:
                    continue
    

    It can remove every new line in excess, no matter where it is in the file.

    Thanks to everyone who tried to help me!