Home > Software design >  How to remove words from a file
How to remove words from a file

Time:01-31

How do I remove words from my .txt file in python I have a list of movies and I would like to remove the one I recently used how do I do this?

movies = ["Shark Tales", "Dead poet's society"]
movie = random.choice(movies)

print("I am gonna watch " movie)

with open("topics.txt", "w") as f:
  f.remove(movie)
  f.close

I want the program to delete the movie I specified from the file so next time its read the movie is not chosen again.

CodePudding user response:

To remove a specific item from a text file, you need to read the contents of the file as a list, modify the list to exclude the desired item, and then write the updated list back to the file:

import random

movies = ["Shark Tales", "Dead poet's society"]
movie = random.choice(movies)

print("I am gonna watch "   movie)

# Read the contents of the file into a list
with open("topics.txt", "r") as f:
    movies = f.read().splitlines()

# Remove the movie
movies.remove(movie)

# Write the updated list back to the file
with open("topics.txt", "w") as f:
    f.write('\n'.join(movies))

CodePudding user response:

As explained here How to delete a specific line in a file?:

movies = ["Shark Tales", "Dead poet's society"]
movie = random.choice(movies)
movies.remove(movie)

print("I am gonna watch " movie)

with open("topics.txt", "r") as f:
    lines = f.readlines()
with open("topics.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != movie:
            f.write(line)
  • Related