简体   繁体   中英

Copy N lines from File1 to File2, then delete copied lines in File1

I want to take 5 lines from File1 and copy them into File2, and then delete the lines I copied from File1. My code is nearly there except instead of deleting the lines from File1 it copies them back there again... thus adding a new 5 lines! Any help much appreciated.

It's a function because I want to define the batch size in my other code.

def batch(size):
    num_lines = sum(1 for line in open('File1.txt'))
    if num_lines >= size:
        with open('File1.txt', 'r+') as File1:
            head = [next(File1) for x in xrange(5)]
            File2 = open('File2.txt', "w")
            for i in head:
                File2.write(i)
                File1.write(i)
            print 'File2 batch created.'

    else:
        print 'Not enough lines in file 1.'

batch(5)

I think this works:

def batch(size):
    num_lines = sum(1 for line in open('File1.txt'))
    if num_lines >= size:
        with open('File1.txt', 'r+') as File1:
            head = [next(File1) for x in xrange(5)]
            File2 = open('File2.txt', "w")
            for i in head:
                File2.write(i)

            lines = open('File1.txt').readlines()
            open('File1.txt', 'w').writelines(lines[size:])

            print 'Batch created.'

    else:
        print 'Nothing ready in follow file.'

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