Home > Blockchain >  Delete whole line in text file Python
Delete whole line in text file Python

Time:10-01

I am writing a delete function to delete the selected option in the text file. Unfortunately the write() function delete all the data in the file without rewriting the new data in it.

def view_product_menu():
    menu_items = open("product_menu.txt", "r")
    for line in menu_items:
        menu_item = line.split(" | ")
        item_name = menu_item[1]
        item_price = menu_item[3]
        item_expiry_date = menu_item[2]
        item_category = menu_item[0]
        item_description = menu_item[4]
        print("Category: ", item_category)
        print(item_name)
        print("Price: ", item_price)
        print("Exp date: ", item_expiry_date)
        print("Product Description: ", item_description)
    menu_items.close()


def delete_product():
    delete_option = input("Which product would you like to delete?\n")
    open_menu = open("product_menu.txt", "r")
    rewrite_menu = open("product_menu.txt", "w")
    for line in open_menu:
        item_name_line = line.split(" | ")
        if delete_option not in item_name_line[1]:
            rewrite_menu.write(line)

view_product_menu()
delete_product()

enter image description here

After running the delete_product() the text file became empty enter image description here

CodePudding user response:

The statement rewrite_menu = open("product_menu.txt", "w") truncates the file, i.e. deletes all its contest. After that, your code attempts to read from this file via the open_menu file handle.

You need to reorganize your code to first read the whole menu into a list of items, then open the file for writing and iterate over the list.

Additionally you are not closing your files in delete_product. Better learn how to use with-statements to open files and have them automatically be closed.

Example implementation avoiding your problem:

def delete_product():
    delete_option = input("Which product would you like to delete?\n")
    # Open and read the existing menu
    with open("product_menu.txt", "r") as open_menu:
        menu_items = open_menu.readlines()
    # Rewrite the menu to the ame file
    with open("product_menu.txt", "w") as rewrite_menu:
        for line in menu_items:
            item_name_line = line.split(" | ")
            if delete_option not in item_name_line[1]:
                rewrite_menu.write(line)

A last word. Reading from and then writing to the same file is generally bad practice. If your program crashes in the middle, your data is lost. So the better approach is to write to a new file and only after the writing was successful, delete the old file and rename the new file to the same name the old file had. Check the shutils module for operations like copying, deleting and renaming files.

CodePudding user response:

please find the updated and working code. DO NOT forget to add import os as first line

import os
def view_product_menu():
    menu_items = open("product_menu.txt", "r")
    for line in menu_items:
        menu_item = line.split(" | ")
        item_name = menu_item[1]
        item_price = menu_item[3]
        item_expiry_date = menu_item[2]
        item_category = menu_item[0]
        item_description = menu_item[4]
        print("Category: ", item_category)
        print(item_name)
        print("Price: ", item_price)
        print("Exp date: ", item_expiry_date)
        print("Product Description: ", item_description)
    menu_items.close()


def delete_product():
    delete_option = input("Which product would you like to delete?\n")
    file_name = "product_menu.txt"
    tmp_file_name = "tmp_product_menu.txt"
    open_menu = open(file_name, "r")
    rewrite_menu = open(tmp_file_name, "w")
    for line in open_menu:
        item_name_line = line.split(" | ")
        if delete_option not in item_name_line[1]:
            rewrite_menu.write(line)
    open_menu.close()
    rewrite_menu.close()
    os.remove(file_name)
    os.rename(tmp_file_name,file_name)

view_product_menu()
delete_product()

With above code You will achieve your objective, though there are other ways to write this code too

CodePudding user response:

Here's a strategy that uses a NamedTemporaryFile. This also has the advantage that the input file can be read line-by-line rather than consuming the entire content into memory.

from tempfile import NamedTemporaryFile
import shutil

ORIGINAL_FILE = 'foo.txt'

def keep(line):
    # some logic in here to determine if this line should be retained
    return True

with open(ORIGINAL_FILE) as origin, NamedTemporaryFile(mode='w', delete=False) as temp:
    name = temp.name
    for line in origin:
        if keep(line):
            temp.write(line)

shutil.move(name, ORIGINAL_FILE)
  • Related