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.
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
- open the file and, reading it
is an interpreted, high-level and general-purpose programming language.