开发者

python file reading

开发者 https://www.devze.com 2022-12-19 16:56 出处:网络
I have file /tmp/gs.pid with content client01: 25778 I would like retrieve the second word from it. ie. 25778.

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


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()


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


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


>>> open("/tmp/gs.pid").read().split()[1]
'25778'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号