Hướng dẫn python split large file into chunks - python chia tệp lớn thành nhiều phần

Dưới đây là tập lệnh Python bạn có thể sử dụng để chia các tệp lớn bằng subprocess:

"""
Splits the file into the same directory and
deletes the original file
"""

import subprocess
import sys
import os

SPLIT_FILE_CHUNK_SIZE = '5000'
SPLIT_PREFIX_LENGTH = '2'  # subprocess expects a string, i.e. 2 = aa, ab, ac etc..

if __name__ == "__main__":

    file_path = sys.argv[1]
    # i.e. split -a 2 -l 5000 t/some_file.txt ~/tmp/t/
    subprocess.call(["split", "-a", SPLIT_PREFIX_LENGTH, "-l", SPLIT_FILE_CHUNK_SIZE, file_path,
                     os.path.dirname(file_path) + '/'])

    # Remove the original file once done splitting
    try:
        os.remove(file_path)
    except OSError:
        pass

Bạn có thể gọi nó bên ngoài:

import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))

Bạn cũng có thể nhập subprocess và chạy trực tiếp trong chương trình của mình.

Vấn đề với phương pháp này là cách sử dụng bộ nhớ cao: subprocess tạo ra một ngã ba với dấu chân bộ nhớ có cùng kích thước với quy trình của bạn và nếu bộ nhớ quy trình của bạn đã nặng, nó sẽ tăng gấp đôi nó trong thời gian nó chạy. Điều tương tự với

import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
0.

Dưới đây là một cách Python thuần túy khác, mặc dù tôi chưa thử nghiệm nó trên các tệp khổng lồ, nó sẽ chậm hơn nhưng hãy nghiêng về bộ nhớ:

CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here

Dưới đây là một ví dụ khác sử dụng

import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
1:

"""
Simple example using readlines()
where the 'file' is generated via:
seq 10000 > file
"""
CHUNK_SIZE = 5


def yield_rows(reader, chunk_size):
    """
    Yield row chunks
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk


def batch_operation(data):
    for item in data:
        print(item)


with open('file', 'r') as f:
    chunks = yield_rows(f.readlines(), CHUNK_SIZE)
    for _chunk in chunks:
        batch_operation(_chunk)

Ví dụ Readlines trình bày cách tạo dữ liệu của bạn để truyền các khối để hoạt động mà mong đợi các khối. Thật không may, các lần đọc mở ra toàn bộ tệp trong bộ nhớ, tốt hơn là sử dụng ví dụ đầu đọc cho hiệu suất. Mặc dù nếu bạn có thể dễ dàng phù hợp với những gì bạn cần vào bộ nhớ và cần xử lý nó trong các khối này thì đủ.

Tách tập tin và hợp nhất làm cho dễ dàng cho các lập trình viên Python!

Mô -đun này
  • Có thể chia các tệp có kích thước bất kỳ thành nhiều khối và cũng hợp nhất chúng trở lại.

  • Có thể xử lý cả các tệp có cấu trúc và không cấu trúc.

yêu cầu hệ thống

Hệ điều hành: Windows/Linux/Mac: Windows/Linux/Mac

Phiên bản Python: 3.x.x: 3.x.x

Cài đặt

Mô -đun có sẵn như là một phần của PYPI và có thể dễ dàng cài đặt bằng PIPpip

pip install filesplit

Tách ra

Tạo một thể hiện

from filesplit.split import Split

split = Split(inputfile: str, outputdir: str)

InputFile (STR, Yêu cầu) - Đường dẫn đến tệp gốc. (str, Required) - Path to the original file.

OutputDir (str, yêu cầu) - Đường dẫn thư mục đầu ra để viết phân tách tệp. (str, Required) - Output directory path to write the file splits.

Với thể hiện được tạo, các phương thức sau có thể được sử dụng trên ví dụ

Hợp nhất

Tạo một thể hiện

from filesplit.merge import Merge

merge = Merge(inputdir: str, outputdir: str, outputfilename: str)

InputFile (STR, Yêu cầu) - Đường dẫn đến tệp gốc. (str, Required) - Path to the directory containing file splits.

OutputDir (str, yêu cầu) - Đường dẫn thư mục đầu ra để viết phân tách tệp. (str, Required) - Output directory path to write the merged file.

Với thể hiện được tạo, các phương thức sau có thể được sử dụng trên ví dụ (str, Required) - Name to use for the merged file.

Hợp nhất

InputDir (str, bắt buộc) - đường dẫn đến thư mục chứa các phân tách tệp.

OutputDir (str, yêu cầu) - Đường dẫn thư mục đầu ra để viết tệp được hợp nhất.

Args:

OutputFileName (STR, Yêu cầu) - Tên để sử dụng cho tệp được hợp nhất. (bool, Optional): If True, all the split files and manifest file will be purged after successful merge. Defaults to False.

Với thể hiện được tạo, phương thức sau đây có thể được sử dụng trên ví dụ (Callable, Optional): Callback function to invoke after merge. The callback function should accept two arguments [func (str, int)] - full path to the merged file, merged file size (bytes). Defaults to None.

Returns:

Hợp nhất (Cleanup: Tùy chọn [bool] = false, gọi lại: Tùy chọn [Callable] = none) -> Không có

Moreover,
  • Hợp nhất các tệp phân chia trở lại thành một tệp.manfilename property like merge.manfilename='man'. The manifest file name should match with the one used during the file split process and should be available in the same directory as that of file splits. Default is manifest.

  • Dọn dẹp (Bool, Tùy chọn): Nếu đúng, tất cả các tệp phân chia và tệp kê khai sẽ được thanh trừng sau khi hợp nhất thành công. Mặc định là sai.terminate to True while the process is running.