How to Append to a Specific Line in Python

Appending data to a specific line in a file can be quite beneficial when you are working on file manipulation projects or when trying to write logs.

Python, as one of the more versatile programming languages, allows for robust file-handling capabilities, including reading, writing, and appending data to files. In this tutorial, we will discuss how you can append data to a specific line in a file using Python.

Step 1: Create a Sample File

To understand how appending to a specific line works, let’s create a sample file. We will create a file called ‘sample_file.txt’ and give it some content:

Step 2: Read the File

The next step we need to do is to read the file via Python. This can be done by using a with open() statement and the readlines() function. This function reads and returns all the lines in the file as a list of strings:

Step 3: Modify the Specific Line

Now, let’s assume we want to append some text to the third line of this file. We can do so by modifying the list of strings that we got from the readlines() function:

Step 4: Write Back the Changes to the File

After modifying the line, we need to write back the changes to our file. This is performed using the with open() statement again with the ‘w’ attribute, and the writelines() function:

Step 5: Verify the Changes

Finally, let’s read back the content of our file to confirm if the new text has been appended:

The Complete Python Code

Here is how the complete Python code should look:

Output

Line 1: This is the first line.
Line 2: This is the second line.
Line 3: This is the third line. Appending some text.
Line 4: This is the fourth line.
Line 5: This is the fifth line.

Conclusion

In this tutorial, you have learned how to append text to a specific line in a file using Python. Understanding file handling in Python is crucial for many data manipulation and data handling operations. It may not be frequently used in everyday programming but is a useful skill to master nonetheless.