views:

64

answers:

4

I have file /tmp/gs.pid with content

client01: 25778

I would like retrieve the second word from it. ie. 25778.

I have tried below code but it didn't work.

>>> f=open ("/tmp/gs.pid","r")
>>> for line in f:
    ...   word=line.strip().lower()
    ...   print "\n -->" , word
+7  A: 

Try this:

>>> f = open("/tmp/gs.pid", "r")
>>> for line in f:
    ...   word = line.strip().split()[1].lower()
    ...   print " -->", word
>>> f.close()

It will print the second word of every line in lowercase. split() will take your line and split it on any whitespace and return a list, then indexing with [1] will take the second element of the list and lower() will convert the result to lowercase. Note that it would make sense to check whether there are at least 2 words on the line, for example:

>>> f = open("/tmp/gs.pid", "r")
>>> for line in f:
    ...   words = line.strip().split()
    ...   if len(words) >= 2:
    ...      print " -->", words[1].lower()
    ...   else:
    ...      print 'Line contains fewer than 2 words.'
>>> f.close()
Max Shawabkeh
+1  A: 
word="client01: 25778"
pid=word.split(": ")[1] #or word.split()[1] to split from the separator
Patrick
+1  A: 

If all lines are of the form abc: def, you can extract the 2nd part with

second_part = line[line.find(": ")+2:]

If not you need to verify line.find(": ") really returns a nonnegative number first.

with open("/tmp/gs.pid") as f:
   for line in f:
      p = line.find(": ")
      if p != -1:
        second_part = line[p+2:].lower()
        print "\n -->", second_part
KennyTM
The `find()` check could be simplified as `if ': ' in line:`, though you'll need to split rather than use the find index in that case.
Max Shawabkeh
A: 
>>> open("/tmp/gs.pid").read().split()[1]
'25778'
ghostdog74