python file reading
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'
精彩评论