'Can you create a nested class in a text file in python?

Im currently writing an menu where you can create, read, update, delete products from a deposit, so my proffesor told me to use .txt file as a "database" not really a database but only to store some information. My question is that i searched everywhere how to create a nested list from user input and insert it in the text file and all i have right now is that i can create a list for each product like : ['Product1', 'quantity', 'price'] ['Product2', 'quantity', 'price'], but i cant create a nested list like this: [['Product1', 'quantity', 'price'], ['Product2', 'quantity', 'price']] so i can print a product with all his details like qty and price.. here is my code:

def adaugaProdus():
nume = input("Introduceti numele produsului:")
cantitate = int(input("Introduceti cantitatea :"))
pret = int(input("Introduceti pretul:"))

produse = []
produse.append(nume)
produse.append(cantitate)
produse.append(pret)

depozit = open("depozit.txt", "a")

depozit.write(str(produse))
depozit.write("\n")
depozit.close()


Solution 1:[1]

I've added a little bit to your code to show you that you can "nest" the lists. I think you were definitely on the right track with your answer:

#!/usr/bin/env python3

def adaugaProdus():
  products = []              # Initialize the list of prducts
  for product in range(2):   # We'll ask user for 2 products - you can choose a different way to terminate the loop as needed
    nume = input("Introduceti numele produsului:")
    cantitate = int(input("Introduceti cantitatea :"))
    pret = int(input("Introduceti pretul:"))

    produse = []
    produse.append(nume)
    produse.append(cantitate)
    produse.append(pret)

    products.append(produse)  # Adding to the list of lists

  depozit = open("depozit.txt", "a")

  depozit.write(str(products))
  depozit.write("\n")
  depozit.close()


adaugaProdus()

And here's another version using PyYAML. YAML is a format that allows the program to write the data, but more importantly it allows the program to read the program easily, too. As an important added bonus, it's easy for us dumb humans to edit!

Here's the modified program:

#!/usr/bin/env python3

import yaml  # you'll need to 'pip install PyYaml' first

def adaugaProdus():
  products = []              # Initialize the list of prducts
  for product in range(2):   # We'll ask user for 2 products - you can choose a different way to terminate the loop as needed
    nume = input("Introduceti numele produsului:")
    cantitate = int(input("Introduceti cantitatea :"))
    pret = int(input("Introduceti pretul:"))

    produse = []
    produse.append(nume)
    produse.append(cantitate)
    produse.append(pret)

    products.append(produse)  # Adding to the list of lists

  with open("depozit.yaml", "w") as f:
    yaml.dump( products, f ) 

adaugaProdus()

And here's the user session and depozit.yaml file:

Introduceti numele produsului:P1 
Introduceti cantitatea :1
Introduceti pretul:1
Introduceti numele produsului:P2
Introduceti cantitatea :2
Introduceti pretul:2

$ cat depozit.yaml 
- - P1
  - 1
  - 1
- - P2
  - 2
  - 2

And here's an example of a program that can read depozit.yaml:

import yaml
with open("depozit.yaml") as f:
  products = yaml.safe_load( f ) 
  print(products)

And the output:

[['P1', 1, 1], ['P2', 2, 2]]

Solution 2:[2]

you should use dictionary :

# Creating an empty dictionary
myDict = {}
  
# Adding list as value
myDict["key1"] = [1, 2]
  
# creating a list
list = ['Product1', 'quantity', 'price'] 
  
# Adding this list as sublist in myDict
myDict["key1"].append(list)
  
print(myDict)

Solution 3:[3]

I would change this to a list of dict items and then use the json standard module. It will make your life a lot easier. See the example below...

import json


def to_dict(nume, cantitate, pret):
    return {
        "nume": nume,
        "cantitate": cantitate,
        "pret": pret
    }


def get_input():
    nume = input("Introduceti numele produsului:")
    cantitate = int(input("Introduceti cantitatea :"))
    pret = int(input("Introduceti pretul:"))
    return nume, cantitate, pret


produse_list = []
# one way
nume, cantitate, pret = get_input()
produse_list.append(to_dict(nume, cantitate, pret))
# other way
produse_list.append(to_dict(*get_input()))
print(produse_list)

with open("output.json", "w") as outfile:
    json.dump(produse_list, outfile)

with open("output.json") as infile:
    produse_list_2 = json.load(infile)

print(produse_list_2)

Solution 4:[4]

You can combine all inputs in a list and then append it to produse. This will create a nested list like [['Product1', 'quantity', 'price'], ['Product2', 'quantity', 'price']]:

def adaugaProdus():
   nume = input("Introduceti numele produsului:")
   cantitate = int(input("Introduceti cantitatea :"))
   pret = int(input("Introduceti pretul:"))

   produse = []
   produse.append([nume, cantitate, pret]) # This is the modified line. 

   depozit = open("depozit.txt", "a")

   depozit.write(str(produse))
   depozit.write("\n")
   depozit.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 None
Solution 3 Edo Akse
Solution 4