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')


Enter sentence: ff
Enter position: ff
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-9afc63f646a2> in <module>()
----> 1 insertSentence('/Users/hackpert/Desktop/test.txt')

<ipython-input-5-94d509a8fe38> in insertSentence(filename)
      3     import os
      4     sentence = raw_input('Enter sentence: ')
----> 5     pos = int(raw_input('Enter position: '))
      6     with open(filename) as fhi, open('tmp.txt', 'w') as fho:
      7         for i in xrange(pos-1):

ValueError: invalid literal for int() with base 10: 'ff'

In [ ]: