Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Python to remove lines in a files that start with an octothorpe?

This seems like a straight-forward question but I can't seem to pinpoint my problem. I am trying to delete all lines in a file that start with an octothorpe (#) except the first line. Here is the loop I am working with:

for i, line in enumerate(input_file):
    if i > 1:
        if not line.startswith('#'):
            output.write(line)

The above code doesn't seem to work. Does anyone known what my problem is? Thanks!

like image 402
drbunsen Avatar asked Aug 08 '11 17:08

drbunsen


People also ask

How do you remove a line starting with a prefix in Python?

To remove lines starting with specified prefix, we use “^” (Starts with) metacharacter. We also make use of re. findall() function which returns a list containing all matches.


1 Answers

You aren't writing out the first line:

for i, line in enumerate(input_file):
    if i == 0:
        output.write(line)
    else:
        if not line.startswith('#'):
            output.write(line)

Keep in mind also that enumerate (like most things) starts at zero.

A little more concisely (and not repeating the output line):

for i, line in enumerate(input_file):
    if i == 0 or not line.startswith('#'):
        output.write(line)
like image 106
Ned Batchelder Avatar answered Oct 05 '22 04:10

Ned Batchelder