2016-07-26 99 views
0

我有一個非常大的文件(大於20GB),我想將它分成較小的文件,如2GB的多個文件。將一個大文件拆分成基於一行的較小文件

一兩件事是我有一個特定的行之前拆分:

我使用Python,但如果有殼例如另一種解決辦法,我爲它。

這是大文件的樣子:

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... 
(2GB +/-)
Recno:: 2 
some data... 

Recno:: 4 
some data... 

Recno:: 5 
some data... 

等等,等等...

謝謝!

+1

這個可能的複製? http://stackoverflow.com/questions/2016894/how-to-split-a-large-text-file-into-smaller-files-with-equal-number-of-lines –

+1

如果你向我們展示它會很有用一些帶有幾行的小例子,顯示文件將在哪裏分割(或不分割)。 –

+0

@Chris_Rands不是因爲我不想用一組給定的行來分割,而是使用特定的行。只有當它超過2Go並出現Recno :: * int *時。 – Difender

回答

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() 
+0

This正是我所期待的,非常感謝你! – Difender

-1

正如上面的評論中提到,你可以在bash shell中使用split

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

正如我所說,我不想只分裂的大小。我必須在規模上進行分割,但也要按照給定的路線分割。例如,每個文件必須以'Recno :: x' – Difender

+0

開始,你可以用'os.stat('/ path/to/file /')在Python中監控文件大小。st_size'在while循環中 – JoshuaBox

相關問題