Reputation: 11
Suppose I have a very large file, and I want to insert "Hello" to the 10000th row. How could I do that without buffering the whole file with python?
I will need to insert row into this big file very frequently, and buffering the whole file will greatly increase the runtime and memory usage. Is there any easy way to insert to the specific row (row number is provided)?
Upvotes: 1
Views: 270
Reputation: 114025
If you're open to writing to a different file, and destroying the old one, this should work:
import itertools
import os
def writeLine(infilepath, N, newline):
outfilepath = infilepath + '.tmp'
with open(infilepath) as infile, open(outfilepath, 'w') as outfile:
for line in itertools.islice(infile, 0, N-1):
outfile.write(line)
outfile.write(newline + '\n')
for line in infile:
outfile.write(line)
os.remove(infilepath)
os.rename(outfilepath, outfilepath[:-4])
Upvotes: 1