Delete all lines that start with comments and print statements from Python file

Question:

I want to delete all lines that start with comments and print statements from my file.

This code works on lines that don’t start with indents:

with open("in.py", "r") as file_input:
    with open("out.py", "w") as file_output: 
        for line in file_input:
            if line.startswith('#'):
                continue
            if line.startswith('print'):
                continue
            file_output.write(line)

But on lines that start with indents this does not work.

So this file_input:

# comment 1
def foo():
    # comment 2
    x = 1
    print(x)
print(x)

returns this file_output:

def foo():
    # comment 2
    x = 1
    print(x)

But I want it to return this:

def foo():
    x = 1

How do you write this?

Asked By: Mike

||

Answers:

This issue is that you’re ignoring whitespace. All you need to do is run .lstrip() to get rid of leading whitespace. Just do this:

with open("in.py", "r") as file_input:
    with open("out.py", "w") as file_output:
        for line in file_input:
            stripped = line.lstrip()
            if stripped.startswith('#') or stripped.startswith('print'):
                continue
            file_output.write(line)
Answered By: Michael M.

You need to strip leading whitespace or the line won’t start with '#' or 'print'. You can also combine the two conditions with or.

with open("in.py", "r") as file_input:
  with open("out.py", "w") as file_output: 
    for line in file_input:
      stripped = line.lstrip()
      if stripped.startswith('#') or stripped.startswith('print'):
        continue
      file_output.write(line)

We can also simplify by combining context managers.

with open("in.py", "r") as file_input, 
     open("out.py", "w") as file_output: 
  for line in file_input:
    stripped = line.lstrip()
    if stripped.startswith('#') or stripped.startswith('print'):
      continue
    file_output.write(line)
Answered By: Chris
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.