Jayden
Jayden

Reputation: 107

How do you search for a certain thing in a text file in python?

I have a text file:

E5341,21/09/2015,C102,440,E,0
E5342,21/09/2015,C103,290,A,290
E5343,21/09/2015,C104,730,N,0
E5344,22/09/2015,C105,180,A,180
E5345,22/09/2015,C106,815,A,400
E5346,23/09/2015,C107,970,N,0
E5347,23/09/2015,C108,1050,E,0
E5348,23/09/2015,C109,370,A,200
E5349,25/09/2015,C110,480,A,250
E5350,25/09/2015,C111,330,A,330
E5351,25/09/2015,C112,1750,E,0
E5352,28/09/2015,C113,1500,N,0
E5353,28/09/2015,C114,272,A,200
E5354,29/09/2015,C115,560,E,0
E5355,29/09/2015,C116,530,A,450
E5356,29/09/2015,C117,860,E,0
E5357,29/09/2015,C118,650,E,0
E5358,29/09/2015,C119,380,A,380
E5359,29/09/2015,C120,980,N,0
E5360,30/09/2015,C121,1375,E,0
E5361,01/10/2015,C122,374,A,374

The E stands for the estimate number

The date following the estimate number is the estimated date

The C stands for the customer number

The number following the customer number is the final total in £

The letter after the final total tells you if the job was accepted(A) or not accepted (N) or the job was just an estimate (E)

The number after the status^ is the total amount already paid in £

I want to find out how if I enter one of the estimate numbers in python can I print out the date or work out the outstanding payments and find out what status the job is.

I've tried to research this but I don't understand it, I would really appreciate any help towards this.

The expected outcome if i put in the estimate number of 5353 is meant to show the date which would be 28/09/2015 for that example

Upvotes: 1

Views: 91

Answers (1)

fyngyrz
fyngyrz

Reputation: 2658

The basic idea in Python 2 (note I have not tested this, but it should be close or work as is):

search = '5356' # supply this as your search
search = 'E'+search
fh = open('textfile.txt')
for line in fh:
    elements = line.split(',')
    if len(elements) == 6:
        if elements[0] == search:
            print 'For Estimate #'+search
            print 'date:'+elements[1]
            print 'cust:'+elements[2]
            print 'totl:'+elements[3]
            print 'stat:'+elements[4]
            print 'paid:'+elements[5]
fh.close()

Now... go look up each statement in that example in the Python 2 documentation and see what the various items in it do. That'll give you a little kickstart towards learning the language, if you are ever going to do any more in it.

Keep in mind that failure is possible: What if the text file name is wrong, for instance, and the file open fails? You'll want to look at the try and except Python language elements.

Everyone needs to start somewhere, which is why I didn't give you a snarky "show your work" answer. So here's your start. Go forth and learn. :)

Upvotes: 1

Related Questions