Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - search txt.file for ID, then return variable from line below

Tags:

python

In Python, I'm attempting (very poorly) to read a .txt file, find the last occurrence of a string referencing a particular customer, and read a few lines below that to gain their current points balance.

A snapshot of the .txt file is:

Customer ID:123
Total sale amount:2345.45

Points from sale:23
Points until next bonus: 77

I can search for (and find) the specific Customer ID, but can't figure out how to search for the last occurrence of this ID only, or how to return the 'Points until next bonus' value... I apologise if this is a basic question, but any help would be greatly appreciated!

My code so far...

def reward_points():

#current points total
rewards = open('sales.txt', 'r')

line = rewards.readlines()
search = (str('Customer ID:') + str(Cust_ID))
print(search) #Customer ID:123

while line != ' ':
    if line.startswith(search):
        find('Points until next bonus:')
        current_point_total = line[50:52]
        cust_record = rewards.readlines()
        print(current_point_total)


rewards.close()

reward_points()

like image 200
BMSydney Avatar asked Mar 15 '26 13:03

BMSydney


1 Answers

I think you'd be better off parsing the file into structured data, rather than trying to seek around the file, which isn't in a particularly convenient file format.

Here's a suggested approach

Iterate over the file with readline

Split the line into fields and labels by matching on ':'

Put the fields and labels representing a customer into a dict

Put the dict representing a customer into another dict

You then have an in-memory database , that you can dereference by dict lookups

e.g customers['1234']['Points until next bonus']

Here's a simplified example code of this approach

#!/usr/bin/env python
import re

# dictionary with all the customers in 
customers = dict()

with open("sales.txt") as f:
    #one line at a time
    for line in f:
        #pattern match on 'key : value'
        field_match = re.match('^(.*):(.*)$',line)

        if field_match :
            # store the fields in variables
            (key,value) = field_match.groups()
            # Customer ID means a new record
            if key == "Customer ID" :
                # set a key for the 'customers database'
                current_id = value
                # if we have never seen this id before it's the first, make a record
                if customers.get(current_id) == None :
                    customers[current_id] = []
                # make the record an ordered list of dicts for each block
                customers[current_id].append(dict())
            # not a new record, so store the key and value in the dictionary at the end of the list
            customers[current_id][-1][key] = value

# now customers is a "database" indexed on customer id
#  where the values are a list of dicts of each data block
#
# -1 indexes the last of the list
# so the last customer's record for "123" is 

print customers["123"][-1]["Points until next bonus"]

Updated

I didn't realise you had multiple blocks for customers, and were interested in the ordering, so I reworked the sample code to keep an ordered list of each data block parsed against customer id

like image 50
cms Avatar answered Mar 18 '26 01:03

cms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!