हिंदी

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
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
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 7: Data File Handling - EXERCISE [पृष्ठ १४६]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
अध्याय 7 Data File Handling
EXERCISE | Q 17. | पृष्ठ १४६
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×