代码之家  ›  专栏  ›  技术社区  ›  user123

根据大小和出现次数将文件拆分为多个文件

  •  0
  • user123  · 技术社区  · 7 年前

    文件内容示例:

    例如,我想将我的文件拆分成100mbs的文件,但是每个文件必须以特定字符开头,文件前面的最后一行必须是原始文件中该字符前面的行。

    1 回复  |  直到 7 年前
        1
  •  1
  •   hootnot    7 年前

    由于结果文件不完全匹配,因此regexp需要进行一些调整。以:perl scriptname.pl<sample.txt的形式运行它,就可以得到块文件。

    #!/usr/bin/perl -w
    
    use strict;
    use IO::File;
    
    
    my $all = join('', (<STDIN>));
    
    my (@pieces) = ($all =~ m%([IZO]\(.*?\)\{.*?\r\n\}\r\n)%gsx);
    
    my $n = 1;
    my $FH;
    foreach my $P (@pieces) {
       if ($P =~ m%^I%) {
          undef $FH;
          $FH = IO::File->new(sprintf("> chunk%d", $n));
          $n++;
       }
       print $FH $P;
    }
    

    #!/usr/bin/env python
    
    import sys
    
    def split(filename, size=100, outputPrefix="xxx"):
        with open(filename) as I:
            n = 0
            FNM = "{}{}.txt"
            O = open(FNM.format(outputPrefix, n), "w")
            toWrite = size*1024*1024
            for line in I:
                toWrite -= len(line)
                if line[0] == 'I' and toWrite < 0:
                    O.close()
                    toWrite = size*1024*1024
                    n += 1
                    O = open(FNM.format(outputPrefix, n), "w")
                O.write(line)
            O.close()
    
    if __name__ == "__main__":
        split(sys.argv[1])
    

    推荐文章