Shahin
Shahin

Reputation: 1316

extract the commented lines only if the following line is not commented

I have a file as follows:

cat file.txt

# unimportant comment
# unimportant comment
# unimportant comment
# important line
blah blah blah
blah blah blah
# insignificant comment
# significant comment
xyz
xyz

I would like to print the lines that start with '#' only if the following line is not commented.

I am hoping to extract the following two lines:

# important line
# significant comment

I tried the following and it does not work:

with open("file.txt","r") as fp:
    for line in fp:
        if line[0] == '#':
            pos = fp.tell()
            previous_line_comment = True
        elif line[0] != '#' and previous_line_comment:
            fp.seek(pos)
            print(fp.readline())
            previous_line_commented = False
        else:
            fp.readline()

Upvotes: 0

Views: 386

Answers (2)

PacketLoss
PacketLoss

Reputation: 5746

Let's store the value of each comment as we iterate, then output the previous line when we encounter a line which is not a comment.

with open('test.txt', 'r') as file:
    ## Set previous comment to None, we will store the comment in here
    previous_comment = None
    for line in file.readlines():
        ## We use startswith to return a boolean T/F if the string starts with '#'
        line_is_comment = line.startswith('#')
        
        if line_is_comment:
            ## If the current line is a comment, set the previous comment to the current line
            previous_comment = line
            continue
        elif previous_comment and not line_is_comment:
            ## If previous comment exists, and the current line is not a comment -> output
            print(previous_comment)
            previous_comment = None
        else:
            previous_comment = None

Output

# important line

# significant comment

Upvotes: 1

sri
sri

Reputation: 357

& is bitwise AND operator. I believe what you intended to use is logical AND.

elif line[0] != '#' and previous_line_comment:

Upvotes: 0

Related Questions