In this article, we will discuss how to insert single or multiple lines at the beginning of a text or CSV file in python.
How to insert a line at the top of a file
There is no direct way to insert text in the middle of a file. Therefore we have to create a new file with the new line at the top and then rename this file as the original file. We have created a function for that,
import os def prepend_line(file_name, line): """ Insert given string as a new line at the beginning of a file """ # define name of temporary dummy file dummy_file = file_name + '.bak' # open original file in read mode and dummy file in write mode with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj: # Write given line to the dummy file write_obj.write(line + '\n') # Read lines from original file one by one and append them to the dummy file for line in read_obj: write_obj.write(line) # remove original file os.remove(file_name) # Rename dummy file as the original file os.rename(dummy_file, file_name)
What does this function do?
- It accepts a file path and line to be inserted as arguments
- Create & open a temporary file in write mode.
- Add the given line as first-line in the temporary file
- Open the original file in read mode and read the contents of the file line by line
- For each line append that into the temporary file
- Delete the original file.
- Rename the temporary file as the original file.
Let’s use this function to insert a line at the beginning of a file.
Suppose we have a file ‘sample.txt’ and its contents are,
Hello this is a sample file It contains sample text Dummy Line A Dummy Line B Dummy Line C This is the end of file
Now add a new line ‘’This is the first line” at the top of the file,
Frequently Asked:
# Insert a line before the first line of a file 'sample.txt' prepend_line("sample.txt", "This is a first line")
Now the contents of the file are,
This is a first line Hello this is a sample file It contains sample text Dummy Line A Dummy Line B Dummy Line C This is the end of file
A new line is added at the top of file.
Insert multiple lines at the top of a file
Suppose we have a list of strings,
list_of_lines = ['Another line to prepend', 'Second Line to prepend', 'Third Line to prepend']
We want to add each string in the list as a new line in the file.
To insert multiple lines at the beginning of a file, we can call the above created function prepend_line() various times i.e. once for each line like this,
[ prepend_line("sample.txt", line) for line in list_of_lines ]
But that is not an efficient solution because it will open, close and move contents to a temporary file for each string/line in the list. So, let’s create a function that opens the file only once and also insert multiple lines at the top of file i.e.
import os def prepend_multiple_lines(file_name, list_of_lines): """Insert given list of strings as a new lines at the beginning of a file""" # define name of temporary dummy file dummy_file = file_name + '.bak' # open given original file in read mode and dummy file in write mode with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj: # Iterate over the given list of strings and write them to dummy file as lines for line in list_of_lines: write_obj.write(line + '\n') # Read lines from original file one by one and append them to the dummy file for line in read_obj: write_obj.write(line) # remove original file os.remove(file_name) # Rename dummy file as the original file os.rename(dummy_file, file_name)
This function accepts a file name and list of strings as arguments. Then add the strings in the list as newlines in a temporary file and then append the lines from the original file to the temporary file. In the end, rename the temporary file as the original file.
Let’s use this function,
Contents of the file ‘sample.txt’ are,
This is a first line Hello this is a sample file It contains sample text Dummy Line A Dummy Line B Dummy Line C This is the end of file
Insert strings in a list as new lines at the top of a file ‘sample.txt’
list_of_lines = ['Another line to prepend', 'Second Line to prepend', 'Third Line to prepend'] # Insert strings in a list as new lines at the top of file 'sample.txt' prepend_multiple_lines("sample.txt", list_of_lines)
Now the Contents of the file ‘sample.txt’ are,
Another line to prepend Second Line to prepend Third Line to prepend This is a first line Hello this is a sample file It contains sample text Dummy Line A Dummy Line B Dummy Line C This is the end of file
The complete example is as follows,
import os def prepend_line(file_name, line): """ Insert given string as a new line at the beginning of a file """ # define name of temporary dummy file dummy_file = file_name + '.bak' # open original file in read mode and dummy file in write mode with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj: # Write given line to the dummy file write_obj.write(line + '\n') # Read lines from original file one by one and append them to the dummy file for line in read_obj: write_obj.write(line) # remove original file os.remove(file_name) # Rename dummy file as the original file os.rename(dummy_file, file_name) def prepend_multiple_lines(file_name, list_of_lines): """Insert given list of strings as a new lines at the beginning of a file""" # define name of temporary dummy file dummy_file = file_name + '.bak' # open given original file in read mode and dummy file in write mode with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj: # Iterate over the given list of strings and write them to dummy file as lines for line in list_of_lines: write_obj.write(line + '\n') # Read lines from original file one by one and append them to the dummy file for line in read_obj: write_obj.write(line) # remove original file os.remove(file_name) # Rename dummy file as the original file os.rename(dummy_file, file_name) def main(): print('*** Insert a line at the top of a file ***') # Insert a line before the first line of a file 'sample.txt' prepend_line("sample.txt", "This is a first line") print('*** Insert multiple lines at the beginning of a file ***') list_of_lines = ['Another line to prepend', 'Second Line to prepend', 'Third Line to prepend'] # Insert strings in a list as new lines at the top of file 'sample.txt' prepend_multiple_lines("sample.txt", list_of_lines) if __name__ == '__main__': main()