mercredi 29 avril 2015

Python - How to make sure that a line being read from a file contain only a given string and nothing else

In order to make sure I start and stop reading a text file exactly where I want to, I am providing 'start1'<->'end1', 'start2'<->'end2' as tags in between the text file and providing that to my python script. In my script I read it as:

start_end = ['start1','end1']
line_num = []
        with open(file_path) as fp1:
            for num, line in enumerate(fp1, 1):
                for i in start_end:
                    if i in line:
                        line_num.append(num)
        fp1.close()
        print '\nLine number: ', line_num
        fp2 = open(file_path)
        for k, line2 in enumerate(fp2): 
            for x in range(line_num[0], line_num[1] - 1):
                if k == x:
                    header.append(line2)
        fp2.close()

This works well until I reach start10 <-> end10 and further. Eg. it checks if I have "start2" in the line and also reads the text that has "start21" and similarly for end tag as well. so providing "start1, end1" as input also reads "start10, end10". If I replace the line:

if i in line:

with

if i == line:

it throws an error.

How can I make sure that the script reads the line that contains ONLY "start1" and not "start10"?

Aucun commentaire:

Enregistrer un commentaire