How To Replace A Character In A File In Python

In this tutorial, we will learn how to replace a character in a file using Python. This can be helpful in various situations, such as when you need to update a text file’s content programmatically or correct any typos in a file.

Using Python’s built-in functions, we can replace a specific character with another character easily.

Step 1: Open the File

First, you need to open the file in read mode. For this, use the with open() function in Python. This allows you to work with the file within a scope, and the file will automatically close once the scope ends.

Here, we open a file named ‘file.txt’ in read mode and store its content in the content variable.

Step 2: Replace the Character

Next, use the replace() function to replace a specific character with another character. The syntax is as follows:

Where old_char is the character you want to replace, new_char is the character you want to replace it with, and count is the number of occurrences you want to replace. If you don’t provide the count parameter, it will replace all occurrences of the specified character.

For example, let’s replace all occurrences of the character ‘a’ with the character ‘b’:

Step 3: Save the Changes

To save the changes, open the file in write mode and write the updated content to it:

This code snippet will overwrite the original content of the file with the modified content containing the replaced characters.

Putting It All Together

Here’s the full code for replacing characters in a file:

And the output for this code would be:

Original Content:
This is a sample text file containing character a several times.
Updated Content:
This is b sbmple text file contbining chbrbcter b severbl times.


In conclusion, we demonstrated how to replace a character in a file using Python. We first opened the file in read mode, replaced the required characters using the replace() function, and finally saved the changes by writing the updated content to the file. This method can be applied to replacing any character or even multiple characters at once if needed.