Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading