Reputation: 11
I'm trying to get the line of a text file that contains a certain string and printing the 3rd number or string in the line. The text file looks like:
1997 180 60 bob
1997 145 59 dan
If the input text contains bob
, my code should print 60
.
Here's what I have so far:
calWeight = [line for line in open('user_details.txt') if name in line]
stringCalWeight = str(calWeight)
print (stringCalWeight)
How can I fix it?
Upvotes: 0
Views: 6259
Reputation: 174696
Through re
module.
>>> L = []
>>> for line in open('/home/avinash/Desktop/f'):
if 'bob' in line:
L.append(re.search(r'^(?:\D*\d+\b){2}\D*(\d+)', line).group(1))
>>> print(L)
['60']
Upvotes: 0
Reputation: 180391
with open('user_details.txt') as f:
for line in f:
if "bob" in line:
print(line.split()[2])
If you want a list of all nums where bob is in the line use a list comprehension:
with open('user_details.txt') as f:
nums = [line.split()[2] for line in f if "bob" in line]
You may also want to split before you check if you want to avoid cases where the name is a substring of a string in the line, for example bob in bobbing
-> True:
nums = [line.split()[2] for line in f if "bob" in line.split()]
I think a more useful structure would be a dict where the values are all the third numbers in a line associated with each name:
from collections import defaultdict
d = defaultdict(list)
with open("in.txt") as f:
for line in f:
if line.strip():
spl = line.rstrip().split()
d[spl[-1]].append(spl[2])
print(d)
defaultdict(<type 'list'>, {'bob': ['60'], 'dan': ['59']})
Upvotes: 1
Reputation: 3719
#need to open the file properly
with open('info.txt', 'r') as fp:
#as suggested by @Padraic Cunningham it is better to iterate over the file object
for line in fp:
#each piece of information goes in a list
infos = line.split()
#this makes sure that there are no problems if your file has a empty line
#and finds bob in the information
if infos and infos[-1] == 'bob':
print (infos[2])
Upvotes: 0