Question

I have a txt file, from which I need to search a specific line, which is working, but in that line I need to strip the first 14 characters, and the part of the list element I am interested is dynamically generated during run time. So, scenario is I ran a script and the output is saved in output.txt, now I am parsing it, here is what I have tried

load_profile = open('output.txt', "r"
read_it = load_profile.read()
myLines = [ ]
for line in read_it.splitlines():
  if line.find("./testSuites/") > -1
   myLines.append(line)
print myLines

which gives output: ['*** Passed :) at ./testSuites/TS1/2013/06/17/15.58.12.744_14'] I need to parse ./testSuites/TS1/2013/06/17/15.58.12.744_14' part only and 2013 and est of the string is dynamically generated.

Could you please guide me what would be best way to achieve it?

Thanks in advance Urmi

Was it helpful?

Solution 2

You are asking how to strip the first 14 characters, but what if your strings don't always have that format in the future? Try splitting the string into substrings (removing whitespace) and then just get the substring with "./testSuites/" in it.

load_profile = open('output.txt', "r")
read_it = load_profile.read()
myLines = [ ]
for line in read_it.splitlines():
    for splt in line.split():
        if "./testSuites/" in splt:
            myLines.append(splt)
print myLines

Here's how it works:

>>> pg = "Hello world, how you doing?\nFoo bar!"
>>> print pg
Hello world, how you doing?
Foo bar!
>>> lines = pg.splitlines()
>>> lines
["Hello world, how you doing?", 'Foo bar!']
>>> for line in lines:
...     for splt in line.split():
...             if "Foo" in splt:
...                     print splt
... 
Foo
>>> 

Of course, if you do in fact have strict requirements on the formats of these lines, you could just use string slicing (strs[13:] as Ashwini says) or you could split the line and do splt[-1] (which means get the last element of the split line list).

OTHER TIPS

Use slicing:

>>> strs = 'Passed :) at ./testSuites/TS1/2013/06/17/15.58.12.744_14'
>>> strs[13:]
'./testSuites/TS1/2013/06/17/15.58.12.744_14'

Update : use lis[0] to access the string inside that list.

>>> lis = ['*** Passed :) at ./testSuites/TS1/2013/06/17/15.58.12.744_14']
>>> strs = lis[0]
>>> strs[17:]       # I think you need 17 here
'./testSuites/TS1/2013/06/17/15.58.12.744_14'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top