To insert a sentence into a very large text file without loading the entire file into memory, you can use a technique called “file buffering” or “file rewriting.” Here’s an example function in Python that demonstrates this approach:
def insert_sentence(filename, sentence, line_number): temp_filename = filename + ".tmp" with open(filename, 'r') as original_file, open(temp_filename, 'w') as temp_file: line_count = 1 # Write the sentence at the specified line number if line_number > 1: for line in original_file: temp_file.write(line) line_count += 1 if line_count == line_number: temp_file.write(sentence + "\n") break # Append remaining lines from the original file for line in original_file: temp_file.write(line) # Replace the original file with the modified file import os os.replace(temp_filename, filename) print("Sentence inserted successfully.") filename = "large_file.txt" sentence = "This is the new sentence." line_number = 3 insert_sentence(filename, sentence, line_number)
In this example, the function insert_sentence
takes the filename
of the large text file, the sentence
to be inserted, and the line_number
where the sentence should be inserted.
The function creates a temporary file temp_filename
based on the original file’s name. It then opens the original file in read mode and the temporary file in write mode.
The function proceeds to copy the original file’s contents to the temporary file up to the specified line_number
. When it reaches the desired line, it writes the sentence
followed by a newline character. Finally, it appends the remaining lines from the original file.
After writing the modified content to the temporary file, the function replaces the original file with the temporary file using os.replace()
. This effectively updates the original file with the inserted sentence.