Open In App

Inventory Management with File handling in Python

Last Updated : 24 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Inventory management is a crucial aspect of any business that deals with physical goods. Python provides various libraries to read and write files, making it an excellent choice for managing inventory. File handling is a powerful tool that allows us to manipulate files on a computer’s file system using programming languages like Python. In this article, we will explore how to implement an inventory management system in Python, Tkinter using file handling.

Inventory Management System Project using Tkinter

Add New Product to Inventory

This function adds a new inventory entry into a text file. It retrieves the item name and quantity from input fields, opens the file in append mode, and writes item_name, item_qty. Then it clears the input fields.

Python3




def add_inventory():
    item_name = item_name_entry.get()
    item_qty = int(item_qty_entry.get())
    with open('inventory.txt', 'a') as file:
        file.write(f'{item_name},{item_qty}\n')
    item_name_entry.delete(0, tk.END)
    item_qty_entry.delete(0, tk.END)


Updating the Inventory

This function update_inventory() updates the existing item_name and item_qty according to the given input updated values. It opens the file in write mode and reads the data from the current inventory. It loops over each line, looks for a match with the item_name, and updates the record if one is found.

Python3




def update_inventory():
    item_name = item_name_entry.get()
    item_qty = int(item_qty_entry.get())
    with open('inventory.txt', 'r') as file:
        inventory_data = file.readlines()
    with open('inventory.txt', 'w') as file:
        for line in inventory_data:
            name, qty = line.strip().split(',')
            if name == item_name:
                file.write(f'{name},{item_qty}\n')
            else:
                file.write(line)
    item_name_entry.delete(0, tk.END)
    item_qty_entry.delete(0, tk.END)


Search and Display the Current Inventory

This function pulls the item_name from the input field that needs to be searched. It iterates through each line of the inventory.txt file while it is open in read-only mode. Here we are using result_label to show the item_name and amount if the item name matches the search name.

Python3




def search_inventory():
    search_name = item_name_entry.get()
    with open('inventory.txt', 'r') as file:
        for line in file:
            name, qty = line.strip().split(',')
            if name == search_name:
                result_label.config(text=f'{name} - {qty}')
                return
    result_label.config(text=f'{search_name} not found in inventory.')
    item_name_entry.delete(0, tk.END)


Removing an Item from the Inventory

The remove_inventory() function removes a specific inventory entry from the inventory.txt file. The function retrieves the item name to be removed from the input field. It opens the inventory.txt file in read mode and reads all the inventory data into a list. The file is then opened again in write mode. It iterates over each line in the inventory data, checks if the item name matches the one to be removed, and skips writing that line.

Python3




def remove_inventory():
    remove_name = item_name_entry.get()
    with open('inventory.txt', 'r') as file:
        inventory_data = file.readlines()
    with open('inventory.txt', 'w') as file:
        for line in inventory_data:
            name, qty = line.strip().split(',')
            if name != remove_name:
                file.write(line)
    item_name_entry.delete(0, tk.END)
    item_qty_entry.delete(0, tk.END)


Generate a Full Inventory List

The generate_inventory() function generates a full list of inventory entries from a text file. It reads the file and stores the inventory data in a list. The inventory data is then joined into a string with newlines. Finally, the string is displayed in the result_label to show the complete inventory list.

Python3




def generate_inventory():
    with open('inventory.txt', 'r') as file:
        inventory_data = file.readlines()
    inventory_text = '\n'.join(inventory_data)
    result_label.config(text=inventory_text)


Complete Code 

Python3




import tkinter as tk
 
# Function to add a new inventory entry
def add_inventory():
    item_name = item_name_entry.get()
    item_qty = int(item_qty_entry.get())
    with open('inventory.txt', 'a') as file:
        file.write(f'{item_name},{item_qty}\n')
    item_name_entry.delete(0, tk.END)
    item_qty_entry.delete(0, tk.END)
 
# Function to update an existing inventory entry
def update_inventory():
    item_name = item_name_entry.get()
    item_qty = int(item_qty_entry.get())
    with open('inventory.txt', 'r') as file:
        inventory_data = file.readlines()
    with open('inventory.txt', 'w') as file:
        for line in inventory_data:
            name, qty = line.strip().split(',')
            if name == item_name:
                file.write(f'{name},{item_qty}\n')
            else:
                file.write(line)
    item_name_entry.delete(0, tk.END)
    item_qty_entry.delete(0, tk.END)
 
# Function to search and display an inventory entry
def search_inventory():
    search_name = item_name_entry.get()
    with open('inventory.txt', 'r') as file:
        for line in file:
            name, qty = line.strip().split(',')
            if name == search_name:
                result_label.config(text=f'{name} - {qty}')
                return
    result_label.config(text=f'{search_name} not found in inventory.')
    item_name_entry.delete(0, tk.END)
 
# Function to remove an existing inventory entry
def remove_inventory():
    remove_name = item_name_entry.get()
    with open('inventory.txt', 'r') as file:
        inventory_data = file.readlines()
    with open('inventory.txt', 'w') as file:
        for line in inventory_data:
            name, qty = line.strip().split(',')
            if name != remove_name:
                file.write(line)
    item_name_entry.delete(0, tk.END)
    item_qty_entry.delete(0, tk.END)
 
# Function to generate a full list of inventory
def generate_inventory():
    with open('inventory.txt', 'r') as file:
        inventory_data = file.readlines()
    inventory_text = '\n'.join(inventory_data)
    result_label.config(text=inventory_text)
 
# create the main window
root = tk.Tk()
root.title("Inventory Management")
 
# input fields
item_name_label = tk.Label(root, text="Item Name:")
item_name_label.grid(row=0, column=0, padx=5, pady=5)
item_name_entry = tk.Entry(root)
item_name_entry.grid(row=0, column=1, padx=5, pady=5)
item_qty_label = tk.Label(root, text="Item Quantity:")
item_qty_label.grid(row=1, column=0, padx=5, pady=5)
item_qty_entry = tk.Entry(root)
item_qty_entry.grid(row=1, column=1, padx=5, pady=5)
 
# creating the buttons
add_button = tk.Button(root, text="Add Inventory",
                       command=add_inventory)
add_button.grid(row=2, column=0, padx=5, pady=5)
update_button = tk.Button(root, text="Update Inventory",
                          command=update_inventory)
update_button.grid(row=2, column=1, padx=5, pady=5)
search_button = tk.Button(root, text="Search Inventory",
                          command=search_inventory)
search_button.grid(row=3, column=0, padx=5, pady=5)
remove_button = tk.Button(root, text="Remove Inventory",
                          command=remove_inventory)
remove_button.grid(row=3, column=1, padx=5, pady=5)
generate_button = tk.Button(root, text="Generate Inventory",
                            command=generate_inventory)
generate_button.grid(row=4, column=0, padx=5, pady=5)
 
result_label = tk.Label(root, text="List")
result_label.grid(row=5, column=0, padx=5, pady=5)
 
root.mainloop()


Output :



Similar Reads

Inventory Management with JSON in Python
The Inventory Management system is used to manage store products and keep track of all goods stock and also we can use it to check the purchases history of the store. Basically, we are developing a system to manage/automate some processes of any retail store by using the computer. So by using this system we can keep record data of products and even
15+ min read
File Handling in Python
File handling in Python is a powerful and versatile tool that can be used to perform a wide range of operations. However, it is important to carefully consider the advantages and disadvantages of file handling when writing Python programs, to ensure that the code is secure, reliable, and performs well. In this article we will explore Python File Ha
9 min read
Handling File Uploads via CGI
In this article, we will explore how we can handle file uploads via CGI (Common Gateway Interface) script on Windows machines. We will develop a form in which there will be the functionality of uploading the file, when the user uploads the file and submits the form, the data is been passed to the CGI script and the file that is uploaded will get st
6 min read
Python File System Quota Management
Managing file system quotas is crucial in preventing storage abuse and ensuring fair resource allocation. Python, being a versatile and powerful programming language, offers several methods to implement file system quota management. In this article, we will explore four simple yet effective methods with practical examples. Python File System Quota
3 min read
reStructuredText | .rst file to HTML file using Python for Documentations
Introduction to .rst file (reStructuredText): reStructuredText is a file format for Textual data majorly used by Python based communities to develop documentation in an easy way similar to other tools like Javadoc for Java. Most of the docs of Python-based software and libraries are written using reStructuredText and hence it's important to learn i
2 min read
Python - Copy contents of one file to another file
Given two text files, the task is to write a Python program to copy contents of the first file into the second file. The text files which are going to be used are second.txt and first.txt: Method #1: Using File handling to read and append We will open first.txt in 'r' mode and will read the contents of first.txt. After that, we will open second.txt
2 min read
Python program to reverse the content of a file and store it in another file
Given a text file. The task is to reverse as well as stores the content from an input file to an output file. This reversing can be performed in two types. Full reversing: In this type of reversing all the content gets reversed. Word to word reversing: In this kind of reversing the last word comes first and the first word goes to the last position.
2 min read
Create a GUI to convert CSV file into excel file using Python
Prerequisites: Python GUI – tkinter, Read csv using pandas CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma. Modules Needed Pandas: Python i
3 min read
Python - Get file id of windows file
File ID is a unique file identifier used on windows to identify a unique file on a Volume. File Id works similar in spirit to a inode number found in *nix Distributions. Such that a fileId could be used to uniquely identify a file in a volume. We would be using an command found in Windows Command Processor cmd.exe to find the fileid of a file. In o
3 min read
How to save file with file name from user using Python?
Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a cop
5 min read
Practice Tags :
three90RightbarBannerImg