extract specific data from txt file in python

Viewed 94

I have a single .txt file (update.txt) that has records of update changes I've made to my program. The contents are as follows:

make Apples 4
make Oranges 3
outstanding Bananas 1
restock Strawberries 40
restock Pineapples 23

How do I print out appropriately according to an option I choose (e.g. I just want to print out all the "restock" data). The output should be as such:

0-restock, 1-make, 2-outstanding. Enter choice: 0
Summarised Data for RESTOCK ***
Strawberries 40
Pineapples 23

Is the below code the correct way to do it?

choice = int(input("0-restock, 1-make, 2-outstanding. Enter choice: "))
    if choice == 0:
        print("Summarised Data for RESTOCK ***")
        with open("update.txt") as openfile:
            for line in openfile:
                for part in line.split():
                    if "restock" in part:
                        print(f"{fruitType} {quantity}")
3 Answers

Your code has an indentation error in the second line. Also, it does not define fruitType and quantity, so it won't print them.

Apart from that, you have hardcoded the "restock" option, so that your code can only print the values for that. You would have to repeat the same code for each possible option if you were to implement it in this way.

Instead, you can define a dictionary holding all your possible options and then use the chosen key (options[choice]) to dynamically print an according message and the respective values from the file.

This is easily extensible to new options. You simply add another key-value-pair to the dictionary.

Full example:


options = {'0': 'restock',
           '1': 'make',
           '2': 'outstanding'}

print('Options:')
for option, value in options.items():
    print(f'  {option}: {value}')
choice = input('Enter choice: ')

print(f'Summarised Data for {options[choice].upper()} ***')
with open('update.txt') as openfile:
    for line in openfile:
        action, fruit, quantity = line.split()
        if action == options[choice]:
            print(f'  {fruit} {quantity}')

Output:

Options:
  0: restock
  1: make
  2: outstanding
Enter choice: 0
Summarised Data for RESTOCK ***
  Strawberries 40
  Pineapples 23

or

Summarised Data for MAKE ***
  Apples 4
  Oranges 3

or

Summarised Data for OUTSTANDING ***
  Bananas 1

def getdata(c):
    choice_map = {"0": "restock", "1": "make", "2": "outstanding"}
    s = open("update.txt", "r").read()
    print("Summarised Data for RESTOCK ***\n ")
    for i in s.split("\n"):
        if choice_map[str(c)] in i:
            print(i.replace(choice[str(c)], "").strip())

choice = int(input("0-restock, 1-make, 2-outstanding. Enter choice: "))
getdata(choice)

The final loop is problematic

choice = int(input("0-restock, 1-make, 2-outstanding. Enter choice: "))
if choice == 0:
    print("Summarised Data for RESTOCK ***")
    with open("update.txt") as openfile:
        for line in openfile:
            action, fruit, quantity = line.split()
            if action == "restock":
                print(f"{fruit} {quantity}")
                        

However I recommend that you use csv for this type of data, it is much more suitable than a text file like this

Related