将N行从File1复制到File2,然后删除File1中的复制行

时间:2015-02-17 00:05:40

标签: python

我想从File1中取出5行并将它们复制到File2中,然后删除我从File1复制的行。我的代码几乎就在那里,除了不删除File1中的行,它再次将它们复制回来...因此添加了新的5行!任何帮助非常感谢。

这是一个函数,因为我想在其他代码中定义批量大小。

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)

1 个答案:

答案 0 :(得分:0)

我认为这有效:

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.'
相关问题