How to Replace a Specific Line in a File Using Python?

Recently while working on a project that involved updating configuration settings stored in a file. I needed an easy way to locate a particular setting based on a keyword and replace that entire line with a new value. In this tutorial, I will explain how to replace a specific line in a file using Python. Python provides a few different methods to accomplish this task. I’ll walk through some examples using common scenarios you may encounter.

Replace a Specific Line in a File Using Python

Let us learn how to replace a specific line in a file using Python.

Read How to Call a Function from Another File in Python?

1. Replace by Line Number

Let’s say you have a file and want to replace the line at a specific line number, like line 10. Here’s how you can do that:

with open('names.txt', 'r') as file:
    lines = file.readlines()

lines[9] = 'John Smith\n'  # replace line 10 

with open('names.txt', 'w') as file:  
    file.writelines(lines)

You can refer to the screenshot below to see the output.

Replace a Specific Line in a File Using Python

First, open the file in read-only mode and read the contents line-by-line using the readlines() method, storing the lines in a variable. Then, directly replace the line at index 9 (line 10) in the lines list. Finally, open the file in write mode and write the updated lines back to the file.

Check out How to Read an Excel File in Python?

2. Replace a Line Containing a Keyword

More commonly, you’ll want to find and replace a line based on a keyword or pattern rather than the line number. For example, if the file contains configuration settings in the format “setting_name=value”, you could search for the setting_name and replace that line.

Here’s an approach using a for loop:

keyword = 'database_url'
new_line = 'database_url=postgres://user:pass@localhost/mydb\n'

with open(r"C:\Users\Public\code\config.txt", 'r') as file:
    lines = file.readlines()
found = False  

with open(r"C:\Users\Public\code\config.txt", 'w') as file:
    for line in lines:
        if line.startswith(keyword):  
            file.write(new_line)  # Replace the line
            found = True  # Mark that the line was found
        else:
            file.write(line)

    if not found:
        file.write(new_line)  # Add new setting at the end

print("Config updated successfully!")

You can refer to the screenshot below to see the output.

How to Replace a Specific Line in a File Using Python

This code opens the file and reads the lines into a list. Then it reopens the file for writing and loops through each line. If a line starts with the specified keyword, it writes the new replacement line to the file. Otherwise, it writes the original unchanged line. This effectively replaces the line containing the keyword.

Read How to Import a Python File from the Same Directory?

3. Use Regular Expressions

For more advanced pattern matching, you can utilize regular expressions and the re module to find and replace lines.

import re

pattern = r'^DB_HOST=.*$'
new_line = 'DB_HOST=db.example.com\n'

with open('settings.py', 'r') as file:
    content = file.read()
    
content = re.sub(pattern, new_line, content, flags=re.M)

with open('settings.py', 'w') as file:
    file.write(content)

You can refer to the screenshot below to see the output.

Replace a Specific Line in a File Using Python re

Here the re.sub() function is used to substitute occurrences of the regex pattern with the new line text. The ^ and $ anchors match the start and end of a line, and .* matches any characters in between. The re.M flag enables multiline mode. This setup finds a line like “DB_HOST=oldhost.com” and replaces the entire line with the new one.

Read How to Get File Size in Python?

4. Use the fileinput Module

Python’s fileinput module provides a convenient way to modify files in place. It allows you to iterate over lines from one or more input files and write output back to the same files. Here’s how you can use it to replace lines:

import fileinput

filepath = 'users.csv'
search_text = 'sarah@example.com'
replace_text = 'sarah.jones@gmail.com'

with fileinput.FileInput(filepath, inplace=True) as file:
    for line in file:
        print(line.replace(search_text, replace_text), end='')

The fileinput.FileInput context manager opens the specified file. Setting inplace=True enables in-place editing, where standard output is redirected back to the file. Inside the loop, each line is read, has the replacement performed on it using replace(), and is then printed, which writes it back to the file. The end=” argument prevents an extra newline from being added.

Check out How to Overwrite a File in Python?

5. Replace Multiple Lines

If you need to replace multiple lines in a file that match a condition, you can adapt the previous techniques. Just modify the looping and conditional logic to handle each relevant line. For example:

# Replace lines between START and END markers 
import fileinput

with fileinput.FileInput('report.txt', inplace=True) as file:
    inside_block = False
    for line in file:
        if line.strip() == 'START_BLOCK':
            inside_block = True
            print(line, end='')
        elif line.strip() == 'END_BLOCK':
            inside_block = False
            print(line, end='')
        elif inside_block:
            print('Replacement line', end='\n') 
        else:
            print(line, end='')

This script replaces all the lines between START_BLOCK and END_BLOCK markers with a single replacement line. It uses a flag variable inside_block to track whether the current line is within the target block. You could adapt this approach for other multi-line replacement scenarios.

Read How to Rename Files in Python?

Conclusion

In this tutorial, I explained how to replace a specific line in a file using Python. I discussed how to replace by line number, replace a line containing a keyword, use regular expressions, use the fileinput module, and replace multiple lines.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.