How To Prepend To A File In Python

If you ever needed to prepend text or data to an existing file in Python, this tutorial is for you. Prepending means adding data to the beginning of the file. This task can be easily achieved using some basic Python functions. Just follow these simple steps and you’ll have your text added to the start of any file in no time.

Step 1: Open The File

To prepend text to a file, first, open the file in read mode and store its contents in a variable. Here’s an example of a file named file.txt with the following content:
This is the second line.
This is the third line.
To read the contents of this file, you can use the following code:

After executing this code, the variable file_data will have the entire content of the file. Now you can close the file.

Step 2: Prepend Your Text

Next, prepare the text you want to add to the start of the file. In this example, let’s prepend a string: “This is the first line.\n”:

Now, concatenate the new text and the file’s content:

At this point, file_data has the updated content with the prepended text.

Step 3: Write Back The Updated Content

Finally, open the file again, but this time in write mode, and save the updated content back to the file:

That’s it! Now, your file should have the new content with the prepended text.

Full Code

Example file (file.txt) content:

This is the second line.
This is the third line.

Output

After executing the code, the content of the file.txt will be:

This is the first line.
This is the second line.
This is the third line.

Conclusion

In this tutorial, we learned how to prepend text to an existing file in Python using built-in functions. This method can be adapted to not only prepend text but also to insert text at any position within the file. Practicing this technique will help you become proficient in Python file manipulation.