python按行提醒分割文本文件

时间:2014-10-19 20:59:44

标签: python file text split

我创建了一个python程序,它计算文本文件中的行,然后根据用户请求的文件编号将其拆分为多个文件,但是我对分割过程的其余部分有问题,例如当用户询问时将文件拆分为3个文件,脚本创建4个文件,并在第四个文件中写下剩余的行

我的代码:

num_lines = sum(1 for line in open("Perfix/{0}.txt".format(name)))
size2 = num_lines / progs
with open('Perfix/{0}.txt'.format(name)) as f:
    for i, g in enumerate(grouper(size2, f, fillvalue=''), 0):
        with open('ip{0}_{1}'.format(name,(i+1)), 'w') as fout:
           fout.writelines(g)

我怎么能解决这个问题?

由于

1 个答案:

答案 0 :(得分:0)

如果您确实希望将额外的行写入最后一个文件,则最后一行的大小应该不同。一种方法是可以构建一个包含所有文件大小的数组,如果有剩余部分,则将该部分附加到最后一个文件的大小。似乎你的石斑鱼是一个扩展itertools的自定义函数。我不知道它做了什么,但这里有一些代码。我只是从初始文件中读取了所需的行数:

def fileSplit(name,progs):
    num_lines = sum(1 for line in open("{0}.txt".format(name)))
    extra=num_lines%progs #save the remainder length
    sizes=[num_lines / progs ] * progs
    sizes[-1]=sizes[-1]+extra #add remainder lines to the length for last file
    with open('{0}.txt'.format(name)) as f:
        for i,g in enumerate(sizes):
            with open('ip{0}_{1}'.format(name,(i+1)), 'w') as fout:
               #read g lines from f at a time and add them to your new fout
               fout.writelines([next(f) for x in xrange(g)])