English

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

Question

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.

Code Writing
Advertisements

Solution

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
  Is there an error in this question or solution?
Chapter 7: Data File Handling - EXERCISE [Page 146]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 7 Data File Handling
EXERCISE | Q 17. | Page 146
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×