Reading two files?
I will be very grateful to get help about this script.
Apython script which can be used to have a convenient format to print the bill in a store. Your script is reading two files:

The first one is containing a list of lines and each line contains four fields: and ID number identifying each article, the name of the article, the category (i.e food, frozen food, house equipment, clothes,. . . ) and finally the price like:

A233    Apple   FOOD    5.00
A345    Blanck  CD 10 DATA  0.25
B453    Pasta   FOOD    12.00
T545    USB-Memory  16GB  DATA  25

The second file is provided by the cash machine and contains the list of ID numbers produced by the cash machine. (It’s possible that the same ID appears more than once if the buyer bought several items of the same product):

A233 
T545 
A354 
A233 
B453 

The script is to produce a nice bill (we can simulated it to the screen) such the following example: (the format is just one example, the most important are the different fields). For each category products should sorted according their names and cotegories according their sum (the most expensive last). You can see an example below:

----  FOOD  ---------
Product  Qty  Price/each  Price  total 
Apple   2   5.00    10.00
Pasta  1    12.00   12.00
SUM:    17.00
---------  DATA
Blank  CD  10   0.25    2.50
USB-Memory  16GB  1 25  25
SUM:    27.50
Nomber  of  articles:  14 
Price  to  pay:  44.50 

** I appreciate your help**

Recommended Answers

All 19 Replies

Make a class which is recognized as an item, either a food item or a data item, or whatever. Read the first file (which is your database of products), and fill in the class' elements (which will be like this: id, name, type, price).
To get the bill, read the 2nd file, for each id, count how many times it is preset (how many items of that type had been bought), and use the elements stored in your database (your classes) to print out relevant information about what was purchased.

Thanks Sir for your answer.

Can you give me your idea as code please

Sorry tony75, but last time I gave a pythonish class example, I was welcomed with a lot of negative feedback, due to "Hmm PEP-8 falling on my head", thus my next move would be to offering you some exemplified links to help you figure that out. So here it is:
Python classes (2.7.3)
Think of classes as a way of keeping toghether items/data that you want/must be handled as one (Take for example a toy car. It has parts in it, but you play with the whole car, not just with the steering-wheel.).

It was a pity and dont worry.

I know you Sir,and you help me several times.
I appreciate all help from you or from another.
I just like to come into right way…

I was welcomed with a lot of negative feedback, due to "Hmm PEP-8 falling on my head", thus my next move would be to offering you some exemplified links to help you figure that out. So here it is:

Sorry it's was more about how your code was indented,your help was very good.
So write more stuff like that,and don't take criticism to serisous PEP-8 it's just as suggestion how Python code shold look.
I myself do not follow all in PEP-8,and i have gotten criticism for this before.

Class Food:
    def __init__(self, identity, name, category, price):
        self.identity = identity
        self.name = name
        self.category = category
        self.price = 0

with open("text1.txt") as f:
    items = []
    for line in f:
        try:
            items.append(Food(*(line.split()))
        except TypeError:
            # wrong number of arguments 
            pass

items.sort(key=lambda s:(s.identity,s.name,s.category,s.price))

I don’t know if my solution right! With sorting?
1.How can I sum the price?
2.How can I use two files?

The problem is your data lines don't split nicely into identity, name, category, price fields.

Thanks Sir
What is right way to do it?

Please anyone have better idea than me to create this script

f1 = open ("text1.txt")
f2 = open ("text2.txt")
print f1
print f2
f1.read()
f2.read()
splitlist = list()

Class Food:
    def __init__(self, identity, name, category, price):
        self.identity = identity
        self.name = name
        self.category = category
        self.price = 0

    for line in f1:
        for line in f2:
            f1 = list.split(', ')
            f2 = list.split(', ')
            splitlist.append(f1)
            splitlist.append(f1)

    for column in splitlist:
        if (len(column) > 1): #to skip the first line
        identity = column[0].strip()
        name = column[1].strip()
        category = column[2].strip()
        price = column[3].strip()

You need to change your first data file format to something like this, where for instance the ';' character is the separator:
A233;Apple;FOOD;5.00
A345;Blanck CD 10;DATA;2.50
B453;Pasta;FOOD;12.00
T545;USB-Memory 16GB;DATA;25

Here would be one number of hints:

'''
file data1.txt looks like this:
A233;Apple;FOOD;1;5.00
A345;Blanck CD 10;DATA;10;0.25
B453;Pasta;FOOD;1;12.00
T545;USB-Memory 16GB;DATA;1;25

each line represents:
identity, name, category, quantity, price
'''

class Billing(object):
    def __init__(self, identity, name, category, quantity, price):
        self.identity = identity
        self.name = name
        self.category = category
        self.quantity = quantity
        self.price = price

# create a list of instances of class Billing
bill_list = []
for line in open("data1.txt"):
    #print(line)  # test
    #print(line.split(';'))  # test
    identity, name, category, quantity, price = line.split(';')
    quantity = int(quantity)
    # remove trailing new line char from price
    price = price.rstrip()
    price = float(price)
    #print(identity, name, category, quantity, price)  # test
    bill_list.append(Billing(identity, name, category, quantity, price))


print("------------------  F O O D  -------------------")
header = ('Product', 'Qty', 'Price/each', 'Price total')
print("%-18s %-5s %-6s %-10s" % (header))
total_food = 0
for bill in bill_list:
    if bill.category == "FOOD":
        totalprice = bill.quantity * bill.price
        sf = "%-18s %2d %10.2f %12.2f"
        print(sf % (bill.name, bill.quantity, bill.price, totalprice))
        total_food += totalprice

print("Total food = %0.2f" % total_food)

print('-'*48)

print("------------------  D A T A  -------------------")
header = ('Product', 'Qty', 'Price/each', 'Price total')
print("%-18s %-5s %-6s %-10s" % (header))
total_data = 0
for bill in bill_list:
    if bill.category == "DATA":
        totalprice = bill.quantity * bill.price
        sf = "%-18s %2d %10.2f %12.2f"
        print(sf % (bill.name, bill.quantity, bill.price, totalprice))
        total_data += totalprice

print("Total data = %0.2f" % total_data)

You still have to bring in your identity file and then search for bill.identity matches.

Wonderful,Thank you very much....
And thanks for your time.

One more question!

Is it possible to solve the script without using class?

Yes, but that would involve some other methods. You'll have to add each item in a specific list, talking about your items from your database, and than work with them from there. A simple example

def itmss():
    iid, iname, itype, iquan, iprice, line = [], [], [], [], [], []
    with open("itms.csv") as f: line = f.readlines()
    for i in line:
        iid.append(i.split(';')[0])
        iname.append(i.split(';')[1])
        itype.append(i.split(';')[2])
        iquan.append(i.split(';')[3])
        iprice.append(i.split(';')[4])
    for i in range (len(iid)):
        print('Id: {}\nName: {}\nType: {}\nQuantity: {}\nPrice: {}'.format(
            iid[i], iname[i], itype[i], iquan[i], iprice[i]))
itmss()


#with itms.csv looking like this:
'''
A233;Apple;FOOD;1;5.00
A345;Blanck CD 10;DATA;10;0.25
B453;Pasta;FOOD;1;12.00
T545;USB-Memory 16GB;DATA;1;25
'''

Thanks Lucaci Andrew I appreciate your help.

Its very intressting to se other methods...

Here is another way to approach this without a record style class ...

''' namedtuple_Billing101.py
file data1.csv looks like this:
A233;Apple;FOOD;1;5.00
A345;Blanck CD 10;DATA;10;0.25
B453;Pasta;FOOD;1;12.00
T545;USB-Memory 16GB;DATA;1;25

each line represents:
identity, name, category, quantity, price
'''

from collections import namedtuple
#import pprint

# read the data file into a string
with open("data1.csv") as fin:
    data_str = fin.read()

# create a list of [id, name, cat, quant, price] lists
data_list = [line.split(';') for line in data_str.split('\n') if line]

# create the named tuple object
Billing = namedtuple('bill', 'id, name, cat, quant, price')

# create a list of Billing instances
bill_list = [Billing(id, name, cat, int(quant), float(price))\
             for id, name, cat, quant, price in data_list]

# test output ...
print("------------------  F O O D  -------------------")
header = ('Product', 'Qty', 'Price/each', 'Price total')
print("%-18s %-5s %-6s %-10s" % (header))
total_food = 0
for bill in bill_list:
    if bill.cat == "FOOD":
        totalprice = bill.quant * bill.price
        sf = "%-18s %2d %10.2f %12.2f"
        print(sf % (bill.name, bill.quant, bill.price, totalprice))
        total_food += totalprice

print("Total food = %0.2f" % total_food)

print('-'*48)

print("------------------  D A T A  -------------------")
header = ('Product', 'Qty', 'Price/each', 'Price total')
print("%-18s %-5s %-6s %-10s" % (header))
total_data = 0
for bill in bill_list:
    if bill.cat == "DATA":
        totalprice = bill.quant * bill.price
        sf = "%-18s %2d %10.2f %12.2f"
        print(sf % (bill.name, bill.quant, bill.price, totalprice))
        total_data += totalprice

print("Total data = %0.2f" % total_data)

''' result ...
------------------  F O O D  -------------------
Product            Qty   Price/each Price total
Apple               1       5.00         5.00
Pasta               1      12.00        12.00
Total food = 17.00
------------------------------------------------
------------------  D A T A  -------------------
Product            Qty   Price/each Price total
Blanck CD 10       10       0.25         2.50
USB-Memory 16GB     1      25.00        25.00
Total data = 27.50
'''

As you can see, I used some of Sneekula's code but simplified it with a named tuple object instead of a class.

Wonderful...

Thank you vegaseat for yor help.

Thanks again:)

By the way..
Any one can recommend me how can I learn python network programming?

Is there any good site ,books,or courses about python network programming?

You should start a new thread with the appropriate title. Your question is otherwise hidden.

OK vegaseat
and thanks for you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.