I used to be a QA engineer and when I first got into Python, one of the first questions that came to my mind while working on Python scripts was: “How Do You Change A Specific Line In A Text File In Python?” We will discuss the answer to this question in much detail below.
How Do You Change A Specific Line In A Text File In Python?
To change a specific line in a text file in Python, you can use the replace()
method on strings, which allows you to specify the text you want to replace and the text you want to replace it with.
Here is a quick example:
# Open the file in read mode
with open('your_text_file_path.txt', 'r') as f:
# Read the contents of the file into a list of lines
lines = f.readlines()
# Use for loop to go through each line in a "your_text_file_path.txt"
for line_index, line in enumerate(lines):
# Check each line for "old_text" and replace it
# with "new_text" if it is found
lines[line_index] = (
lines[line_index]
.replace('old_text', 'new_text')
)
# Open a new file in writing mode (this will create a new file)
with open('your_new_text_file_path.txt', 'w') as f:
# Write the modified lines to the new "your_new_text_file_path.txt"
f.writelines(lines)
In this code, line_index
is the index of the line you want to change in the lines
list.
The replace()
method will replace all occurrences of “old_text” in that line with “new_text”.
The file is then opened in write mode, and the modified lines are written to the new text file which is called: your_new_text_file_path.txt
.
You may want to modify a line in a file based on a specific condition, let’s explore how such a result can be achieved in the following sections of this post.
How Do I Change The First Line Of A File In Python?
To change the first line of a file in Python, you can use the same approach as above but specify an if condition involving line_index
.
Here is an example:
# Open the file in read mode
with open('your_text_file_path.txt', 'r') as f:
# Read the contents of the file into a list of lines
lines = f.readlines()
# Use for loop to go through each line in a "your_text_file_path.txt"
for line_index, line in enumerate(lines):
# Check first line for "old_text" and replace it
# with "new_text" if it is found
if line_index == 0:
lines[line_index] = (
lines[line_index]
.replace('old_text', 'new_text')
)
# Open a new file in writing mode (this will create a new file)
with open('your_new_text_file_path.txt', 'w') as f:
# Write the modified lines to the new "your_new_text_file_path.txt"
f.writelines(lines)
Another approach to modifying the first line of a text file in Python would be to read the entire file into memory as a single string and the use replace()
method to modify the first line..
and write it as a new version of the text file the same way it was done in the examples above.
# Open the file in read mode
with open('file.txt', 'r') as f:
# Read the entire contents of the file into a string
data = f.read()
# Replace the first line
data = data.replace('old_text', 'new_text', 1)
# Open the file in write mode
with open('file.txt', 'w') as f:
# Write the modified string back to the file
f.write(data)
In the example provided above, the replace()
method is called with a third argument of 1
, which specifies that only the first occurrence of 'old_text'
should be replaced.
This is important because without this argument, the replace()
method will replace all occurrences of 'old_text'
in the string, which could potentially modify multiple lines in the file if they contain the same text. ⚠️

By using the count
argument, we can ensure that only the first line is modified, which is what we want in this case.
This can be particularly useful when working with large files, as it can save time and memory by avoiding unnecessary replacements.
It is also worth noting that the replace()
method has a default value of -1
for the count
argument, which means that all occurrences of the search string will be replaced by default.
This is why it is important to explicitly specify the count
argument if you want to limit the number of replacements.
How Do You Replace Part Of A String With A Value?
To replace part of a string with a value in Python, you can again – use the replace()
method on strings.
A very small change here would be if you’d want to use some sort of variable.
You can combine the previous example of overwriting a file with the example of using variables to specify the text to be replaced and the replacement text in a replace()
method call.
Here is an example:
# Open the file in read mode
with open('your_text_file_path.txt', 'r') as f:
# Read the contents of the file into a list of lines
lines = f.readlines()
# Text to replace
old_text = 'is'
# Replacement text
new_text = 'was'
# Use for loop to go through each line in a "your_text_file_path.txt"
for line_index, line in enumerate(lines):
# Check first line for "old_text" and replace it
# with "new_text" if it is found
if line_index == 0:
lines[line_index] = (
lines[line_index]
.replace(old_text, new_text)
)
# Open a new file in writing mode (this will create a new file)
with open('your_new_text_file_path.txt', 'w') as f:
# Write the modified lines to the new "your_new_text_file_path.txt"
f.writelines(lines)
You can also combine string formatting with the previous example of overwriting a file to modify a specific line in a text file in Python.
Here is an example:
# Open the file in read mode
with open('your_text_file_path.txt', 'r') as f:
# Read the contents of the file into a list of lines
lines = f.readlines()
# Text to replace
old_text = 'is'
# Replacement value
value = 5
# Replacement text using string formatting
new_text = f'was {value} times'
# Use for loop to go through each line in a "your_text_file_path.txt"
for line_index, line in enumerate(lines):
# Check first line for "old_text" and replace it
# with "new_text" if it is found
if line_index == 0:
lines[line_index] = (
lines[line_index]
.replace(old_text, new_text)
)
# Open a new file in writing mode (this will create a new file)
with open('your_new_text_file_path.txt', 'w') as f:
# Write the modified lines to the new "your_new_text_file_path.txt"
f.writelines(lines)
In this code, the value
variable is used to specify the value to be inserted into the replacement text using string formatting.
The new_text
variable is then assigned the result of applying string formatting to the 'was {value} times'
string, which inserts the value of the value
variable into the string.
The replace()
method is then called on the line_index
-th line of the lines
list, with the old_text
and new_text
variables as arguments, which perform the replacement and return a new string with the specified replacements.
This approach allows you to easily insert dynamic values into the replacement text using string formatting, and it also allows you to modify a specific line in a file without reading the entire file into memory or writing the entire file back to disk.
It can be particularly useful when working with large files, as it can save time and memory by avoiding unnecessary operations.
Overall, combining string formatting with the previous example of overwriting a file can be a powerful and efficient way to modify a specific line in a text file in Python.
It allows you to insert dynamic values into the replacement text, and it can make your code more modular and easier to understand.
How Do You Rewrite A Text File In Python? (If Statement)
It can make sense to create a copy of the original file before overwriting it in some situations, such as when you want to preserve the original file in case something goes wrong during the overwrite operation, or when you want to be able to restore the original file later if necessary.
To create a copy of a file in Python, you can use the shutil
module, which provides a convenient copy2()
function that allows you to copy a file from one location to another.
Here is an example of how to use the copy2()
function to create a copy of a file. I used this approach to overwrite Django settings.py
file for certain development situations.
import os
import shutil
# Should be project folder path
project_folder_path = os.environ.get('PWD')
# settings.py path
settings_file_path = os.path.join(
project_folder_path,
'projectname',
'settings.py'
)
settings_original_path = os.path.join(
project_folder_path,
'projectname',
'settings_original.py'
)
if os.path.exists(settings_original_path):
# Delete previously overriden file
os.remove(settings_file_path)
else:
# Make a copy of settings.py (create settings_original.py)
shutil.copy2(settings_file_path, settings_original_path)
# Delete settings.py to be able to write a new one
os.remove(settings_file_path)
The copy()
and copy2()
functions in the shutil
module are similar, but they have some important differences that you should be aware of.
The copy()
function is a basic file copying function that copies the contents of a source file to a destination file, and it has the following signature:
shutil.copy(src, dst)
The src
argument specifies the source file, and the dst
argument specifies the destination file. The copy()
function returns the path of the destination file.
The copy2()
function is similar to the copy()
function, but it also attempts to preserve as many of the metadata of the source file as possible, such as the timestamps, permissions, and flags.
This can be useful if you want to create an exact copy of the source file, including its metadata.
The copy2()
function has the following signature:
shutil.copy2(src, dst)
In general, the copy()
function is sufficient for most file copying tasks, and it is faster and simpler than the copy2()
function.
However, if you need to preserve the metadata of the source file, you should use the copy2()
function instead.
Alright, let’s continue with the example!
So, here’s what I came up with for overwriting settings.py
file in Django.
This is Python code for overwriting files that I actually use on a daily basis.
# Read settings_original.py file
with open(settings_original_path, 'r') as settings_file:
lines = settings_file.readlines()
# Collect lines and override particular settings
settings_lines = []
enable_specific_brand_changes = False
for line in lines:
# Replace a "USE_TZ"
if 'USE_TZ' in line:
line = line.replace('USE_TZ = True', '# USE_TZ = True')
# For specific brand, enable wizard login
if " 'specific_brand': {" in line:
enable_specific_brand_changes = True
# Within the following for loop cycles, find a feature to change
if enable_specific_brand_changes:
if "'disable_wizard_auth': True" in line:
line = line.replace('True', 'False')
enable_specific_brand_changes = False
settings_lines.append(line)
if os.path.exists(settings_file_path):
raise Exception('settings.py file already exists, delete first!')
# Write new settings file
with open(settings_file_path, 'w') as settings_file:
for line in settings_lines:
settings_file.write(line)
The above code reads a file called settings_original.py
, and then it modifies the file by replacing some of its lines with new versions of those lines.
It then writes the modified lines back to a new file called settings.py
.
The code first opens the settings_original.py
file in read mode, and it reads the contents of the file into a list of lines using the readlines()
method.
It then creates an empty list called settings_lines
to store the modified lines.
Next, the code defines a enable_specific_brand_changes
flag that is initially set to False
.
This flag will be used to track whether the code is currently processing the lines that need to be modified for a specific brand.
The code then enters a for
loop that iterates over each line in the lines
list.
For each line, the code performs the following operations:
- If the line contains the
'USE_TZ'
string, the code calls thereplace()
method on the line to replace the'USE_TZ = True'
string with the'# USE_TZ = True'
string. This disables theUSE_TZ
setting in the file. - If the line contains the string
" 'specific_brand': {"
, the code sets theenable_specific_brand_changes
flag toTrue
. This indicates that the code is now processing the lines that need to be modified for the specific brand. - If the
enable_specific_brand_changes
flag isTrue
, the code checks if the line contains the string"'disable_wizard_auth': True"
. If so, it calls thereplace()
method on the line to replace the'True'
string with the'False'
string. This enables the wizard authentication for the specific brand. - Regardless of whether the line was modified in the previous steps, the code appends the line to the
settings_lines
list.
After the for
loop completes, the code checks if a file called settings.py
already exists.
If so, it raises an exception to indicate that the file already exists and needs to be deleted first.
Finally, the code opens the settings.py
file in write mode, and it writes the modified lines from the settings_lines
list to the file using the write()
method. This creates the new settings.py
file with the modified settings.
Overall, the above code reads a file, modifies some of its lines based on certain conditions, and writes the modified lines back to a new file. This approach is very effective and useful when you’re working with different versions of your Django project.
The code uses the readlines()
and write()
methods to read and write the files, and it uses the replace()
method to perform string replacements in the lines.
It also uses a for
loop and a flag variable to track the lines that need to be modified for a specific brand.
Leave a Reply
You must be logged in to post a comment.