Python: How to ignore #comment lines when reading in a file

Viewed 109165

In Python, I have just read a line form a text file and I'd like to know how to code to ignore comments with a hash # at the beginning of the line.

I think it should be something like this:

for 
   if line !contain #
      then ...process line
   else end for loop 

But I'm new to Python and I don't know the syntax

10 Answers

a good thing to get rid of coments that works for both inline and on a line

def clear_coments(f):
    new_text = ''
    for line in f.readlines():
        if "#" in line: line = line.split("#")[0]

        new_text += line

    return new_text
Related