Search Specific Field In Text File
Suppose I have a file named abc.txt which contains the following data. I am an newbie. So please help Nathan Johnson 23 M Mary Kom 28 F John Keyman 32 M Edward Stella
Solution 1:
You can do something like this, if you want to search via a particular piece of information. So say, the user wants to search through firstname
for John
. This is how you would do it:
#!usr/bin/python
import sys
class Records:
def __init__(self, firstname, lastname, age, gender):
self.fname = firstname
self.lname = lastname
self.age = age
self.gender = gender
f= open("abc","r")
list_of_records = [Records(*line.split()) for line in f]
search_term = "John"
for record in list_of_records:
if record.firstname == search_term:
print "We found him!"
print record.firstname, record.lastname, record.age, record.gender
If the user gave both a firstname
and a gender
, then you can do something like this:
for record in list_of_records:
if record.firstname == "John" and record.gender = "M":
print "We found him!"
print record.firstname, record.lastname, record.age, record.gender
Also, always remember to close your file streams, so when you call open
, you are actually opening a file stream, so at the end of the script, always close them, like so f.close()
. If you use with
, then you do not need to worry about closing.
Solution 2:
For a more compact and flexible solution, you can use the namedtuple type from the standard library:
import collections
record_tuple = collections.namedtuple('Record',
['Firstname', 'Lastname', 'Age', 'Gender'])
n = raw_input("Enter %s :" % ' '.join('%s.%s' % (i, name) for i, name in enumerate(record_tuple._fields, 1)))
n = int(n)
StringSearch = raw_input('Enter %s :' % record_tuple._fields[n-1])
for line in open('abc'):
record = record_tuple(*line.split())
if record[n-1] == StringSearch:
print ' '.join(record)
This way, you can generalize the search code.
Post a Comment for "Search Specific Field In Text File"