- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find and replace within a text file using Python?
The following code does the replacement in the given text file.
After the replacement, the text is written to a new text file 'bar.txt'
f1 = open('foo.txt', 'r') f2 = open('bar.txt', 'w') for line in f1: print line f2.write(line.replace('Poetry', 'Prose')) f2 = open('bar.txt', 'r') for line in f2: print line, f1.close() f2.close()
This gives the output
Poetry is often considered the oldest form of literature. Poetry today is usually written down, but is still sometimes performed. Prose is often considered the oldest form of literature. Prose today is usually written down, but is still sometimes performed.
- How to search and replace text in a file using Python?
- How to find and replace the word in a text file using PowerShell?
- How to find the Strings within a text file in Java?
- How to find and replace text in Oracle?
- How to Search and Replace text in Python?
- Find and Replace text in the entire table using a MySQL?
- How to find a file using Python?
- How to write text and output it as a text file using R?
- How to write a single line in text file using Python?
- How to find Kaprekar numbers within a given range using Python?
- How to read a text file in Python?
- How to replace only text inside a div using jQuery?
- How to call Python file from within PHP?
- How to read an entire line from a text file using Python?
- How to write multiple lines in text file using Python?