Copy a File Without Comment Lines

Medium ⏱ 12 min 57% acceptance ★★★★☆ 4.2
Write strip_comments(src, dst) that copies a script from src to dst, omitting every line whose first non-whitespace character is #. All other lines (including blank ones) are copied unchanged. Return the number of lines written.

Examples

Example 1
Input
strip_comments('in.py', 'out.py')  # in.py: 'x = 1\n# note\n  # indented\ny = 2\n'
Output
2
Explanation

Both comment lines vanish; two code lines are written.

Constraints

  • A comment line's first non-space char is #.
  • Return the written-line count.

Topics

File Handlingread + write

Companies

MicrosoftIntel

Hints

Hint 1

line.lstrip().startswith('#') detects comments.

Hint 2

Open both files in one with statement: with open(a) as f, open(b, "w") as g.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.