write a program in python that accepts a python file and display everything except comment lines starting with #
Answers
Explanation:
A naive way to read a file and skip initial comment lines is to use “if” statement and check if each line starts with the comment character “#”. Python string has a nice method “startswith” to check if a string, in this case a line, starts with specific characters. For example, “#comment”.startswith(“#”) will return TRUE. If the line does not start with “#”, we execute the else block.
The problem with this approach to skip a few lines is that we check each line of the file and see if it starts with “#”, which can be prohibitively slow if the file is really big. So clearly it is not an efficient approach to read a file and skip comment lines.
# open a file using with statement
with open(filename,'r') as fh
for curline in fh:
# check if the current line
# starts with "#"
if curline.startswith("#"):
...
...
else:
...
...
A second approach to read a file and the first part of a file based on some conditions is to use while statement. The idea here is to read a file line by line with while statement and break the while statement the moment we see the first line without the comment symbol (or without the pattern of interest). Then we use a second while loop to read through the rest of the file line be line.
with open('my_file.txt') as fh: # Skip initial comments that starts with # while True: line = fh.readline() # break while statement if it is not a comment line # i.e. does not startwith # if not line.startswith('#'): break # Second while loop to process the rest of the file while line: print(line) ... ...