Python Program to Replace Specific Line in File

Files In Python:

A file is a piece of data or information stored on a computer’s hard drive. You’re already familiar with a variety of file kinds, including music, video, and text files. Manipulation of these files is trivial with Python. Text files and binary files are the two types of files that are commonly used. Binary files contain binary data that can only be read by a computer, whereas text files include plain text.

For programmers and automation testers, Python file handling (also known as File I/O) is a crucial topic. Working with files is required in order to write to or read data from them.

In addition, if you didn’t know, I/O activities are the most expensive techniques via which software might fail. As a result, when implementing file processing for reporting or any other reason, you should proceed with caution. The construction of a high-performance application or a robust solution for automated software testing can benefit from optimizing a single file activity.

Given a file, the task is to replace the specific line in Python.

Program to Replace Specific Line in File in Python

Approach:

  • Give the line number which you want to replace as static input and store it in a variable.
  • Give the line text as static input add newline character at the end of it.
  • Make a single variable to store the path of the file. This is a constant value.
  • This value must be replaced with the file path from your own system in the example below.
  • Open the file in read-only mode. In this case, we’re simply just reading the contents of the file.
  • Get all the lines from the given file using the readlines() function.
  • Modify the (linenumb) line in the above lines with the replaced text using list indexing.
  • Open the file in write-only mode.
  • Write the modified data to the same file again using writelines() function.
  • Print acknowledgment that says that the line is replaced.
  • The Exit of the Program.

Below is the implementation:

# Give the line number which you want to replace as static input and store it in a variable
linenumb = 3
# Give the line text as static input add newline character at the end of it
replacedtext = "this is BTechGeeks"+'\n'
# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in read-only mode. In this case, we're simply just reading the contents of the file.
with open(givenFilename, 'r') as givenfilecontent:
    # Get all the lines from the given file using the readlines() function
    filelines = givenfilecontent.readlines()
    # modify the (linenumb) line in the above lines with the replaced text using list indexing
    filelines[linenumb-1] = replacedtext
# Open the file in write-only mode
with open(givenFilename, 'w') as givenfilecontent:
    # Write the modified data to the same file again using writelines function
    givenfilecontent.writelines(filelines)
# Print acknowledgement that says that the line is replaced
print('The given linenumber = ', linenumb,
      ' is replaced with {', replacedtext, '}')

Output:

The given linenumber = 3 is replaced with { this is BTechGeeks }

Samplefile.txt(Before Replacement):

hello
good morning
welcome
for all 
btech students

Samplefile.txt(After Replacement):

hello
good morning
this is BTechGeeks
for all 
btech students

Explanation:

  • The file path is stored in the variable ‘file name.’ Change the value of this variable to the path of your own file.
  • Dragging and dropping a file onto the terminal will show its path. The code will not run unless you change the value of this variable.
  • The file will be opened in reading mode. Use the open() function to open a file. The path to the file is the method’s first parameter, and the mode to open the file is the method’s second parameter.
  • When we open the file, we use the character ‘r’ to signify read-mode.
  • Using list indexing replace the line.

Sample Implementation in google colab: