Advertisements
Advertisements
प्रश्न
Write a function to insert a sentence in a text file, assuming that text file is very big and can't fit in computer's memory.
कोड लेखन
Advertisements
उत्तर
Insertion is performed by copying the original file to a temporary file and inserting the sentence at the required line. Only one line is held in memory at a time.
import os
def insert_sentence(filename, sentence, line_number):
temporary = filename + ".tmp"
with open(filename, "r") as source, open(temporary, "w") as target:
for number, line in enumerate(source, start=1):
if number == line_number:
target.write(sentence.rstrip("\n") + "\n")
target.write(line)
if line_number > number:
target.write(sentence.rstrip("\n") + "\n")
os.replace(temporary, filename)
insert_sentence("story.txt", "This sentence is inserted.", 3)
The temporary file is renamed after successful completion.
shaalaa.com
या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
