Home > Back-end >  How to remove all empty lines from beginning and end of file
How to remove all empty lines from beginning and end of file

Time:02-10

I have a file that looks like

Blank Line
Blank Line
Blank Line
Blank Line
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi a justo egestas, malesuada lacus ut, euismod purus.
Etiam faucibus felis ac orci varius cursus.

Praesent tincidunt nibh condimentum, finibus odio non, euismod tortor.
Quisque eget ligula eu turpis consequat rutrum.

Cras non ipsum vel ipsum sodales ullamcorper non vitae dui.
Blank Line
Blank Line
Blank Line
Blank Line

The Blank Line is literally blank line. I could not put blank lines in the beginning and end in the code block so using the text Blank Line.

I need to remove all the blank lines from the beginning and end of this file. Please notice that there are blank lines in between lines. I do not want to remove those.

I have come up with the following code that remove all blank lines from the beginning of the file. But I could not manage to remove all the blank lines at the end of the file.

#!/usr/bin/env python3

import sys
import argparse
import logging

parser = argparse.ArgumentParser()
parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin)
parser.add_argument(
    '-d',
    '--debug',
    help="Print lots of debugging statements",
    action="store_const",
    dest="loglevel",
    const=logging.DEBUG,
    default=logging.WARNING,
)
parser.add_argument(
    '-v',
    '--verbose',
    help="Be verbose",
    action="store_const",
    dest="loglevel",
    const=logging.INFO,
)
args = parser.parse_args()

if sys.stdin.isatty() and args.infile.name == "<stdin>":
    sys.exit("Please give some input")

logging.basicConfig(level=args.loglevel)

# Business Logic Here   
do_not_print_all_lines = True

for line in args.infile:
    if not line.strip() and do_not_print_all_lines:
        pass
    else:
        do_not_print_all_lines = False

    if not do_not_print_all_lines:
        print(line)

How can I do that?

CodePudding user response:

Can you just first read the file into a list? Then, you can address empty lines from the beginning and the end of the list

CodePudding user response:

Something like this:

my_file = open("sample-file.txt", "r")
lines = my_file.readlines()
# inspection starting from beginning of list
for n in range(len(lines)):
    line = lines[n].strip()
    if line == "":
        frm= n
    else:
        break
# inspection starting from end of list
for n in range(len(lines)-1,-1,-1):
    line = lines[n].strip()
    if line == "":
        to= n
    else:
        break
newlines = lines[frm 1:to]
print(newlines)
  • Related