Last modified: October 10, 2021

Python: How to Delete a text from a file and save it

By using replace() method, you can delete a phrase or text from a file.

Let's see how to use it.

Delete a text from a file

Before writing our code, let's see the file.txt output.

file.txt:

Python is an interpreted, high-level and general-purpose programming language.

The code above will delete Python from the file.


# Read file.txt
with open('file.txt', 'r') as file:
    text = file.read()


# Delete text and Write
with open('file.txt', 'w') as file:
    # Delete
    new_text = text.replace('Python', '')
    # Write
    file.write(new_text)


Let me explain

  1. open the file and, reading it
  2. delete Javascript then, writing the output

file.txt:

 is an interpreted, high-level and general-purpose programming language.

As you can see, Javascript has been deleted.