user3161743
user3161743

Reputation: 171

Python Reading files and deleting items

The question is write a program that will ask the user for a fruit they dislike. Next, read the groceries.txt file and create a new file called groceries.new with the fruit that the user dislikes removed.

what i written so far is... I don't know how to delete the item from the file.

groceries = open('groceries.txt', 'r')

groceries_contents = groceries.read()

groceries_new = open('groceries.new.txt', 'w')

groceries_new.write(groceries_contents)

groceries_new_contents = groceries_new.read()

fruit = raw_input ("What fruit do you dislike? ")
if fruit in groceries_new_contents:
     del fruit 


groceries.close()
groceries_new.close()

Upvotes: 0

Views: 124

Answers (2)

jfs
jfs

Reputation: 414795

fruit = raw_input("What fruit do you dislike? ")
with open("groceries.txt") as file, open("groceries.new", "w") as output_file:
    for line in file:
        if fruit not in line: 
            output_file.write(line) # save line if it doesn't contain the fruit

Upvotes: 1

Pan Long
Pan Long

Reputation: 1032

The trick here is you are not really "delete" the item. After you have read the content, you check whether it is the fruit the user dislikes. If yes, then you do not write to the new file; if not, then you write to the new file. Hope it helps.

Upvotes: 1

Related Questions