lines = [line.rstrip( ) for line in open('script1.py') if line[0] == 'p'] res = [] for line in open('script1.py'): if line[0] == 'p': res.append(line.rstrip( )) print res