Skip to content Skip to sidebar Skip to footer

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

Solution 1:

import re
prog = re.compile('start1$')
if prog.match(line):
   print line

That should return None if there is no match and return a regex match object if the line matches the compiled regex. The '$' at the end of the regex says that's the end of the line, so 'start1' works but 'start10' doesn't.

or another way..

deftest(line):
   import re
   prog = re.compile('start1$')
   return prog.match(line) != None
> test('start1')
True
> test('start10')
False

Solution 2:

Since your markers are always at the end of the line, change:

start_end = ['start1','end1']

to:

start_end = ['start1\n','end1\n']

Solution 3:

You probably want to look into regular expressions. The Python re library has some good regex tools. It would let you define a string to compare your line to and it has the ability to check for start and end of lines.

Solution 4:

If you can control the input file, consider adding an underscore (or any non-number character) to the end of each tag.

'start1_'<->'end1_'

'start10_'<->'end10_'

The regular expression solution presented in other answers is more elegant, but requires using regular expressions.

Solution 5:

You can do this with find():

fornum, line inenumerate(fp1, 1):
    foriin start_end:
        if i in line:
            # make sure the next char isn't'0'if line[line.find(i)+len(i)] != '0':
                line_num.append(num)

Post a Comment for "Python - How To Make Sure That A Line Being Read From A File Contain Only A Given String And Nothing Else"