简体   繁体   中英

python insert a line to specific row (a large file)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM