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àyCó 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 filesplitTá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.