0

Basically what I want to do is have the notepad list show up in python so the user can see what is on the list without opening the file. I have done that. Now I want to have the user input a product that they want, and save it, and print out the product and the price. This is what the text file looks like:

000,67463528,50mm bolts,2.20
001,34512340,plain brackets,0.50
002,56756777,100mm bolts,0.20
003,90673412,l-shaped brackets,1.20
004,45378928,normal brackets,0.80
005,1638647,10mm bolts,0.10
006,14372841,plain brackets,1.29
007,29384754,200mm bolts,0.50
008,12345768,screwdriver,10.99

So far I can add products to the end of the code, and I can insert text at a certain line number. I am working out how to print out a receipt based on user input. I am new to python studying this as a hobby, any help would be greatly appreciated. Thanks!

This is the python code:

def search():
    gtin = input("What is the GTIN code? ")
    des = input("What is the name of the product? ")
    price = input ("What is the price of the product? ")
    position_str = input("What line do you want this inserted at? ")
    print("This is the list now: ")
    position = int(position_str)

    with open("task2.txt", "r") as a_file:
        data = a_file.readlines()

    data.insert(position, "00" + position_str + "," + gtin + "," + des + "," + price + "\n")

    data = "".join(data)

    with open("task2.txt",  "w") as a_file:
        a_file.write(data)

    input()

    with open('task2.txt','r')as Task2:
        print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price"))
        for row in Task2:
            row=row.strip()
            eachItem=row.split(",")
            print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3]))
    print()



def add():
    print("The data you put here will be added onto the end ")
    gtin = input("What is the GTIN-8? ")
    des = input("What is the description? ")
    price = input("What is the price? ") #gets all the info they want to add
    print("This is the list now: ")

    with open("task2.txt","a") as a_file:
            a_file.writelines("   ," + gtin + "," + des + "," + price + "\n")
            a_file.close()
            print("Product has been added")

    with open('task2.txt','r')as Task2:
        print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price"))
        for row in Task2:
            row=row.strip()
            eachItem=row.split(",")
            print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3]))
    print()



def reciept():

    print()



#this is the menu. this is where the user will make choices on what they do

def menu():
    print("What would you like to do?")

    with open('task2.txt','r')as Task2:
        print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price"))
        for row in Task2:
            row=row.strip()
            eachItem=row.split(",")
            print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3]))
    print()


    print("1. Add a product onto a specific line number?")
    print("2. Or add a product onto the end?")
    print("3. Buy products and have them printed onto a reciept?")
    choice=int(input("Which one?: "))
    if choice==1:
        search()
    elif choice==2:
        add()
    elif choice==3:
        reciept()

menu()
Messi
  • 1

1 Answers1

0

What to fix and documentation locations

Firstly, I also cannot seem to replicate exactly what you're doing so, I worked up my own solution to some extent...

If you provided a text document with the information in it, it might help with debugging.

That aside... I noticed that if you don't have your "task2.txt" file created, you don't have a way to create one.

This can be done with Task2 = open("task2.txt", "w"). Input / Output Documentation for Python 2.7

Secondly, some of the formatting can be improved by using expressions; I.E.,

\t [tab],

\n [newline],

\r [return],

So you can abide by PEP-8 standard rules. PEP-8 Documentation

Alright, so that's out of the way, what you need to do next is understand the different between open and with open... Not too much difference here, except that with open forces you to immediately jump into a loop. If the document doesn't have information in it, you result in an error (this is the issue I have right now).

Storing it as a list (task2 = open([file], 'r') is better as it allows you to utilize it later. You should also run a check to see if the file even exists...

Example

Thirdly, here are a few tips n' tricks:

import os

boolCheckOnFile = os.path.isfile("[Location to File]\\task2.txt")
# Check if it exists
if boolCheckOnFile==False:
    # Create file, "w" for write
    task2Creation = open("[Location to File]\\task2.txt", "w")
    # Close the file to reopen and read it or write to it...
    task2Creation.close()

# Again "w" for write, "a" for append, "r" for read, "r+" for read/write...
task2 = open("[Location to File]\\task2.txt", "r+")

From here, you can write to the file by enacting str.write(information). But it's always best to close the file when you're actually done with the file... So the changes you made to it are permanent str.close().

Word of advice, print() # print "()", you must fill it, so at least do a newline, like so:

print("\n")

What I did to fix some beginners issues

Finally, below is my iteration of the corrected version (for just the menu portion of your script)...

def menu():

    print("What would you like to do?")

    # Check if file exists
    if os.path.isfile('C:\\users\\[username]\\Desktop\\task2.txt')==False:
        # Create it and promptly close it, so it is in the correct location
        task1 = open('C:\\users\\[username]\\Desktop\\task2.txt','w')
        task1.close()

    # Open for read-write
    task2 = open('C:\\users\\[username]\\Desktop\\task2.txt','r+')

    # splits for new line break, making an array
    info = task2.read().split("\n")

    # Check to see if the file is empty
    if len(info) is not 0:
        print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format("\nNo.",
                                                                   "GTIN-8",
                                                                   "Item Name",
                                                                   "Price"))
        # Read each line of document
        for line in info:
            arrayOfItems = line.split(",")
            print('{0:<19}     {1:<19}     {2:<19}     {3:<19}'.format(arrayOfItems[0],
                                                                       arrayOfItems[1],
                                                                       arrayOfItems[2],
                                                                       arrayOfItems[3]))

    else:
        print('You have no items listed!')

    print("\n")


    print("1. Add a product onto a specific line number?")
    print("2. Or add a product onto the end?")
    print("3. Buy products and have them printed onto a reciept?")
    choice=int(input("Which one?: "))
    if choice==1:
        search()
    elif choice==2:
        add()
    elif choice==3:
        reciept()

menu()

Good luck and enjoy making python scripts and programs! It's fun and challenging at times. I was once in your shoes, just remember it gets easier as you keep working on it.

ALSO:

Check out some other Stack Overflowers works... Sometimes an easy solution like this can be resolved by looking at some other peoples work and questions...

Opening file for both reading and writing

Basic read and write

Lowercase examples plus reading and writing

Copying files for modifying documents and creating saves

Community
  • 1
  • 1
SirJames
  • 387
  • 8
  • 27