Write a program to insert a sentence in a text file assuming that the text file is very big and cannot be read in one go
In [5]:
def insertSentence(filename):
'''Function to insert sentence in a large text file which cannot be read in one go'''
import os
sentence = raw_input('Enter sentence: ')
pos = int(raw_input('Enter position: '))
with open(filename) as fhi, open('tmp.txt', 'w') as fho:
for i in xrange(pos-1):
line = fhi.readline()
fho.write(line)
fho.write(sentence)
for line in fhi:
fho.write(line)
os.remove(filename)
os.rename('tmp.txt',filename)
In [6]:
insertSentence('/Users/hackpert/Desktop/test.txt')
In [ ]: