Hướng dẫn python split file into multiple files by size - python chia tệp thành nhiều tệp theo kích thước

Lớp này có thể giải quyết vấn đề của bạn. Tôi đã thử nghiệm nó trên hệ điều hành Linux và Windows và nó hoạt động hoàn hảo trên cả hai. Ngoài ra, tôi đã thử nghiệm tệp nhị phân và văn bản với các kích thước khác nhau mỗi lần và nó thật tuyệt. Vui thích :)

import os
import math

class FileSpliter:
    # If file type is text then CHUNK_SIZE is count of chars
    # If file type is binary then CHUNK_SIZE is count of bytes
    def __init__(self, InputFile, FileType="b", CHUNK_SIZE=524288, OutFile="outFile"):
        self.CHUNK_SIZE = CHUNK_SIZE    # byte or char
        self.InputFile = InputFile
        self.FileType = FileType        # b: binary,  t: text
        self.OutFile = OutFile
        self.FileSize = 0
        self.Parts = None
        self.CurrentPartNo = 0
        self.Progress = 0.0

    def Prepare(self):
        if not(os.path.isfile(self.InputFile) and os.path.getsize(self.InputFile) > 0):
            print("ERROR: The file is not exists or empty!")
            return False
        self.FileSize = os.path.getsize(self.InputFile)
        if self.CHUNK_SIZE >= self.FileSize:
            self.Parts = 1
        else:
            self.Parts = math.ceil(self.FileSize / self.CHUNK_SIZE)
        return True

    def Split(self):
        if self.FileSize == 0 or self.Parts == None:
            print("ERROR: File is not prepared for split!")
            return False        
        with open(self.InputFile, "r" + self.FileType) as f:
            while True:
                if self.FileType == "b":
                    buf = bytearray(f.read(self.CHUNK_SIZE))
                elif self.FileType == "t":
                    buf = f.read(self.CHUNK_SIZE)
                else:
                    print("ERROR: File type error!")
                if not buf:
                    # we've read the entire file in, so we're done.
                    break
                of = self.OutFile + str(self.CurrentPartNo)
                outFile = open(of, "w" + self.FileType)
                outFile.write(buf)                              
                outFile.close()
                self.CurrentPartNo += 1 
                self.ProgressBar()
        return True

    def Rebuild(self):
        self.CurrentPartNo = 0
        if self.Parts == None:
            return False    
        with open(self.OutFile, "w" + self.FileType) as f:
            while self.CurrentPartNo < self.Parts:
                If = self.OutFile + str(self.CurrentPartNo) 
                if not(os.path.isfile(If) and os.path.getsize(If) > 0):
                    print("ERROR: The file [" + If + "] is not exists or empty!")
                    return False
                InputFile = open(If, "r" + self.FileType)
                buf = InputFile.read()
                if not buf:
                    # we've read the entire file in, so we're done.
                    break               
                f.write(buf)                                
                InputFile.close()
                os.remove(If)
                self.CurrentPartNo += 1 
                self.ProgressBar()
        return True 

    def ProgressBar(self, BarLength=20, ProgressIcon="#", BarIcon="-"):
        try:
            # You can't have a progress bar with zero or negative length.
            if BarLength <1:
                BarLength = 20
            # Use status variable for going to the next line after progress completion.
            Status = ""
            # Calcuting progress between 0 and 1 for percentage.
            self.Progress = float(self.CurrentPartNo) / float(self.Parts)
            # Doing this conditions at final progressing.
            if self.Progress >= 1.:
                self.Progress = 1
                Status = "\r\n"    # Going to the next line             
            # Calculating how many places should be filled
            Block = int(round(BarLength * self.Progress))
            # Show this
            Bar = "\r[{}] {:.0f}% {}".format(ProgressIcon * Block + BarIcon * (BarLength - Block), round(self.Progress * 100, 0), Status)
            print(Bar, end="")
        except:
            print("\rERROR")

def main():
    fp = FileSpliter(InputFile="inFile", FileType="b") #, CHUNK_SIZE=300000)
    if fp.Prepare():
        # Spliting ...      
        print("Spliting ...")
        sr = fp.Split()
        if sr == True:
            print("The file splited successfully.")
        print()
        # Rebuilding ...
        print("Rebuilding ...") 
        rr = fp.Rebuild()
        if rr == True:
            print("The file rebuilded successfully.")

if __name__ == "__main__":
    main()

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.

Làm cách nào để chia một tệp CSV lớn thành nhiều tệp trong Python?

Nếu bạn cần nhanh chóng chia một tệp CSV lớn, thì hãy gắn bó với API hệ thống tập tin Python ...
Xác nhận dữ liệu và ném ra hàng rác ..
Gán đúng loại cho mỗi cột ..
Viết dữ liệu vào định dạng tệp tốt để phân tích dữ liệu, như sàn gỗ ..
Nén dữ liệu ..

Làm thế nào để bạn chia dữ liệu thành nhiều tệp trong Python?

Phương thức chia () sẽ trả về một danh sách các phần tử trong một chuỗi. Theo mặc định, Python sử dụng khoảng trắng để phân chia chuỗi, nhưng bạn có thể cung cấp một dấu phân cách và chỉ định (các) ký tự nào sẽ sử dụng thay thế. Ví dụ: dấu phẩy (,) thường được sử dụng để phân tách dữ liệu chuỗi. Đây là trường hợp với các tệp giá trị phân tách dấu phẩy (CSV).. By default, Python uses whitespace to split the string, but you can provide a delimiter and specify what character(s) to use instead. For example, a comma(,) is often used to separate string data. This is the case with Comma Separated Value (CSV) files.

Làm cách nào để chia một tệp văn bản thành nhiều tệp?

Làm thế nào để chia một tài liệu TXT trực tuyến..
Chọn và tải lên tài liệu TXT của bạn để chia tách ..
Chỉ định số trang mong muốn và nhấp vào nút chia ngay bây giờ ..
Khi tài liệu TXT của bạn được chia nhỏ, nhấp vào nút tải xuống ..
Sử dụng nút email để gửi liên kết tải xuống qua email ..

Làm cách nào để chia một tệp thành các phần nhỏ hơn?

Mở tệp ZIP.Open Tab Công cụ. Bấm vào nút thả xuống kích thước phân chia và chọn kích thước phù hợp cho từng phần của tệp ZIP phân chia.Nếu bạn chọn kích thước tùy chỉnh trong danh sách thả xuống kích thước phân chia, một cửa sổ nhỏ khác sẽ mở và cho phép bạn nhập kích thước tùy chỉnh được chỉ định trong megabyte. Open the Tools tab. Click the Split Size dropdown button and select the appropriate size for each of the parts of the split Zip file. If you choose Custom Size in the Split Size dropdown list, another small window will open and allow you to enter in a custom size specified in megabytes.