【问题标题】:Splitting a big file into smaller ones basing on a line [closed]根据一行将大文件拆分为较小的文件[关闭]
【发布时间】:2016-07-26 13:08:32
【问题描述】:

我有一个相当大的文件(超过 20GB),我想将它拆分成更小的文件,例如多个 2GB 的文件。

有一件事是我必须在特定行之前拆分:

我正在使用 Python,但如果在 shell 中有其他解决方案,例如,我准备好了。

这是大文件的样子:

bigfile.txt (20GB)

Recno:: 0
some data...

Recno:: 1
some data...

Recno:: 2
some data...

Recno:: 3
some data...

Recno:: 4
some data...

Recno:: 5
some data...

Recno:: x
some more data...

这就是我想要的:

file1.txt (2 GB +/-)

Recno::0
some data...

Recno:: 1
some data...

file2.txt (2GB +/-)

Recno:: 2
some data...

Recno:: 4
some data...

Recno:: 5
some data...

等等,等等……

谢谢!

【问题讨论】:

  • 这个可能重复吗? stackoverflow.com/questions/2016894/…
  • 如果您向我们展示一些带有几行的小示例,显示文件将被拆分(或不拆分)的位置,将会很有用。
  • @Chris_Rands 并不是真的因为我不想用给定的一组线条而是用特定的线条来分割。仅当它超过 2Go 并且出现 Recno:: int 时。
  • @TomFenech 我在示例中添加了更多内容,如果我不够精确,请告诉我。
  • 正如另一个答案所说,您可以在 bash 中使用 split -b 来拆分字节

标签: python bash shell split


【解决方案1】:

你可以这样做:

import sys

try:
    _, size, file = sys.argv
    size = int(size)
except ValueError:
    sys.exit('Usage: splitter.py <size in bytes> <filename to split>')

with open(file) as infile:
    count = 0
    current_size = 0
    # you could do something more
    # fancy with the name like use
    # os.path.splitext
    outfile = open(file+'_0', 'w+')
    for line in infile:
        if current_size > size and line.startswith('Recno'):
            outfile.close()
            count += 1
            current_size = 0
            outfile = open(file+'_{}'.format(count), 'w+')
        current_size += len(line)
        outfile.write(line)
    outfile.close()

【讨论】:

  • 这正是我想要的,非常感谢!
【解决方案2】:

如上所述,您可以在 bash shell 中使用 split

split -b 20000m <path-to-your-file>

【讨论】:

  • 正如我所说,我不想只根据大小进行拆分。我必须在大小上拆分,但也要在给定的行上拆分。例如,每个文件必须以 Recno:: x 开头
  • 您可以在 Python 中使用 os.stat('/path/to/file/').st_size 在 while 循环中监控文件大小
猜你喜欢
  • 1970-01-01
  • 2019-01-24
  • 2012-06-06
  • 2018-11-09
  • 1970-01-01
  • 2019-09-23
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多