1

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
0

4 Answers 4

7

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()
Sign up to request clarification or add additional context in comments.

Comments

1
word="client01: 25778"
pid=word.split(": ")[1] #or word.split()[1] to split from the separator

Comments

1

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

1 Comment

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.
1
>>> open("/tmp/gs.pid").read().split()[1]
'25778'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.