Python – How to Update and Replace Text in a File

5/5 - (2 votes)

Problem Formulation and Solution Overview

In this article, you’ll learn how to update and replace text in a file using Python.

To make it more fun, we have the following running scenario:

Tristen, a columnist with the Toronto Star, is writing a column about Niagara Falls. He has noticed a few issue(s) with his writing. Rather than replacing or updating text, he sent you a file and gave you the task to do this for him.

Contents of niagara.txt (complete with errors and omissions):

Niagara Fals is a waterfall located on the Niagara River and is considered a major tourist destination and attraction. The Fals are situated on the border of Niagara Falls, Canada and New York State, United States. For many years, honeymooners and dare-devls alike enjoyed the Fals for very different reasons. The most infamous trick by dare-devls is to walk across the Fals on a tight-rope or go over the Fals in a barrel. Now most people visit here now for its amazing beauty and uniqueness.

💬 Question: How would we write code to replace or update text in a file?

We can accomplish this task by one of the following options:


Method 1: Use open() and replace()

This method reads in a file, replaces existing text, then saves the file. For this example, each occurrence of Fals is replaced with the correct spelling, Falls.

with open('niagara.txt', 'r') as fp:
    data = fp.read()
    typos = data.replace('Fals', 'Falls')

with open('niagara.txt', 'w') as fp:
    fp.write(typos)

Above, uses with open to open niagara.txt, in reading (r) mode and save it as a file object. This object allows access to and manipulation of the file. If fp was output to the terminal, it would look similar to below.

<_io.TextIOWrapper name='niagara.txt' mode='r' encoding='cp1252'>

Then, the file contents are read using the file object (fp) and the read() method. This saves to contents.

The following line uses replace() and passes two (2) arguments: the text to search for ('Fals') and the text to replace it with ('Falls'). The results save to typos.

💡Note: Using with open() is the recommended method to open files as the file automatically closes once there are no more lines of code inside to execute.

The final step is to open the same file (niagara.txt) in write (w) mode and write the contents to the file.

The contents of niagara.txt should now look like the following. However, the corrected typos are in bold to exemplify the changes.

Niagara Falls is a waterfall located on the Niagara River and is considered a major tourist destination and attraction. The Falls are situated on the border of Niagara Falls, Canada and New York State, United States. For many years, honeymooners and dare-devls alike enjoyed the Falls for very different reasons. The most infamous trick by dare-devls is to walk across the Falls
on a tight-rope or go over the Falls in a barrel. Now most people visit here now for its amazing beauty and uniqueness.
Python String Methods [Ultimate Guide]

Method 2: Use pathlib2 replace()

This method requires an additional library, pathlib2, to read in a file and replace existing text using its replace() function. For this example, each occurrence of dare-dvls is replaced with the correct spelling, dare-devils.

To run this code error-free, install the required library. Click here for installation instructions.

from pathlib2 import Path

myfile = Path('niagara.txt')
typos = myfile.read_text()
fixed = typos.replace('dare-devls', 'dare-devils')
myfile.write_text(fixed)

Above imports Path from the pathlib2 library.

Next, the file name niagara.txt saves to myfile. Then the contents of this file are read in and saved to typos.

The following line locates and replaces the typo dare-dvls with dare-devils, and the changes are written to the file.

The contents of niagara.txt should now look like the following. However, the corrected typos are in bold to exemplify the changes.

Niagara Falls is a waterfall located on the Niagara River and is considered a major tourist destination and attraction. The Falls are situated on the border of Niagara Falls, Canada and New York State, United States. For many years, honeymooners and dare-devils alike enjoyed the Falls for very different reasons. The most infamous trick by dare-devils is to walk across the Falls
on a tight-rope or go over the Falls in a barrel. Now most people visit here now for its amazing beauty and uniqueness.

Looking much better now!


Method 3: Use pyutil and filereplace()

This method requires an additional library, pyutil to read in a file and replace existing text using its filereplace() function. For this example, the word unmatched is replaced with breathtaking.

To run this code error-free, install the required library. Click here for installation instructions.

from pyutil import filereplace
filereplace('niagara.txt', 'amazing', 'breathtaking')

Above imports filereplace() from the pyutil library.

Next, the file niagara.txt is read in. The text to be replaced is searched for and, if found, replaces amazing with breathtaking.

The contents of niagara.txt should now look like the following. However, the change is in bold to exemplify the change.

Niagara Falls is a waterfall located on the Niagara River and is considered a major tourist destination and attraction. The Falls are situated on the border of Niagara Falls, Canada and New York State, United States. For many years, honeymooners and dare-devils alike enjoyed the Falls for very different reasons. The most infamous trick by dare-devils is to walk across the Falls
on a tight-rope or go over the Falls in a barrel. Now most people visit here now for its breathtaking beauty and uniqueness.

Almost there!


Method 4: Use open() and write()

This method reads in a file, adds a new line after the last line, and saves the file. For this example, Tristen Calwell’s name will be added.

with open('niagara.txt','a') as fp:
        fp.write('\nBy: Tristen Callwell')

Above, uses with open to open niagara.txt, in append (a) mode and save it as a file object. This object allows access to and manipulation of the file.

Next, a new line (\n) and the writer’s details are written to niagara.txt.

The contents of niagara.txt should now look like the following. However, the corrected typos are in bold to exemplify the changes.

Niagara Falls is a waterfall located on the Niagara River and is considered a major tourist destination and attraction. The Falls are situated on the border of Niagara Falls, Canada and New York State, United States. For many years, honeymooners and dare-devils alike enjoyed the Falls for very different reasons. The most infamous trick by dare-devils is to walk across the Falls
on a tight-rope or go over the Falls in a barrel. Now most people visit here now for its amazing beauty and uniqueness.

By: Tristen Callwell

Great stuff!

Python open() Function – An 80/20 Guide by Example

Method 5: Use regex

This method uses regex to search for and replace a specific word. For this example, the word now was replaced with the word lately.

import re

with open('niagara.txt', 'r') as fp:
    data = fp.read()
    result = re.sub(r'now', 'lately', data)

with open('niagara.txt', 'w') as fp:
    fp.write(result)

Above imports the regex library.

Above, uses with open to open niagara.txt, in read (r) mode and save it as a file object. This object allows access to and manipulation of the file.

The following lines are read in from niagara.txt and save to data. Next, regex searches for and replaces the word now with the word lately. This saves to result.

Then the file niagara.txt is opened in write (w) mode and saved as a file object. Finally, the contents of result is written to the file.

The contents of niagara.txt should now look like the following. However, the change is in bold to exemplify the changes.

Niagara Falls is a waterfall located on the Niagara River and is considered a major tourist destination and attraction. The Falls are situated on the border of Niagara Falls, Canada and New York State, United States. For many years, honeymooners and dare-devils alike enjoyed the Falls for very different reasons. The most infamous trick by dare-devils is to walk across the Falls
on a tight-rope or go over the Falls in a barrel. Now most people visit here lately for its amazing beauty and uniqueness.

By: Tristen Callwell

We’re done and ready to hand back the article to Tristen.

5 must have skills to become a programmer (that you didn't know)

Summary

These five (5) methods of updating and replacing text in a file should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Programming Humor