1

I am using a template to create multiple .txt files. Some files will have empty values, so I want to remove the resulting empty lines:

arg1 = '- this is the third line'
arg2 = '- this is the fourth line'
arg3 = ''
arg4 = '- this is the sixth line'

When applied to the template the result is the following content:

(content being a multi line string)

This is the first line:

    - this is the third line
    - this is the fourth line

    - this is the sixth line

This is some other content whose possible empty lines need to be left alone.

From the template:

This is the first line:

    $arg1
    $arg2
    $arg3
    $arg4

This is some other content whose possible empty lines need to be left alone.

So before I write this content to a file I want to remove those ugly empty lines, so it looks like this:

This is the first line:

        - this is the third line
        - this is the fourth line         
        - this is the sixth line

This is some other content whose possible empty lines need to be left alone.

In other words I want to remove all empty lines that fall in the specific range of lines, something like this:

for line, index_line in zip(content.splitlines(), range(1, 11)):
    if index_line in range(4, 11) and line == '    ':
        # command that will remove the empty line and save the new content

P.S. the ranges are different, since this is my own code snippet, but the ranges for the given example would be:

range (1, 7) #stop when we pass the sixth line

range(3,7) #check only the lines in the given range

2 Answers 2

2

The function you want is list.pop(index).

# assuming you have the contents read from the file split into this list:
lines = content.splitlines()

indicestoremove=[]
for index in range (2,6): # or whatever range of lines you want to trim - 
                          # remember indices start from 0 for the first line
    if lines[index] == '':
        indicestoremove.append(index)

# remove in reverse order, as pop() changes the index of items later in the list
for index in sorted(indicestoremove, reverse=True):
    lines.pop(index)

f = open('filename')
for line in lines:
  f.write("%s\n" % line)
Sign up to request clarification or add additional context in comments.

1 Comment

A previous version of this would not work if there were more than one contiguous lines to remove, as pop() changes the structure of the list such that it would skip comparing the next item. Saving the indices and removing in reverse order avoids this.
0

If the ranges may vary and if we can count on "^-\s" as a flag for when we want to start and stop removing empty lines, then you could use regular expressions.

import re

s = '''This is the first line:

    - this is the third line
    - this is the fourth line

    - this is the sixth line


This is some other content whose possible empty lines need to be left alone.

Leave that last line alone.
'''

remove_empty = False
lines = []
for line in s.splitlines():
    l = line.strip()
    if l != '':
        dashed = (re.match('^-\s', l) is not None)
        if dashed and not remove_empty:
            # Now we need to start removing empty strings
            remove_empty = (re.match('^-\s', l) is not None)
        elif not dashed and remove_empty:
            # Now it is time to stop
            remove_empty = False
            lines.append('')

    if l != '' or not remove_empty:
        lines.append(line)

print '\n'.join(lines)
# This is the first line:
#
#     - this is the third line
#     - this is the fourth line
#     - this is the sixth line
#
# This is some other content whose possible empty lines need to be left alone.
#
# Leave that last line alone.

If you know the ranges for sure then it looks like Aaron D would have a better solution.

Comments

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.