How to Prepend Content to a File in Python
To prepend content to a file in Python, open the file in read+write mode, seek to the start of the file, then write the newline plus the original file content.
Let's demonstrate this with an example and look closer at each step taken.
file.txt
Some existing content.
Another line of content.
new_line = 'New line to prepend.\n'
with open('file.txt', 'r+') as file:
content = file.read()
file.seek(0)
file.write(new_line + content)
file.txt
New line to prepend.
Some existing content.
Another line of content.
First, open the file in r+
mode in a with statement. This will allow you to read and write to the newly created file object.
with open('file.txt', 'r+') as file:
Then read the existing file content using the .read()
method and store it in a variable.
content = file.read()
Now seek to the beginning of the file using the .seek()
method and pass 0 as the first argument.
file.seek(0)
Finally, write the newline plus the original content to the file using the .write()
method.
file.write(new_line + content)
Note - r+
mode will throw an exception if the file doesn't exist.