Files
TCP-file/src/file.py
T

63 lines
1.8 KiB
Python

import os
import hashlib
class File:
def __init__(self, file_path, chunk_size=2048):
self.file_path = file_path
self.chunk_size = chunk_size
def split_to_chunks(self):
"""将文件分割为指定大小的块"""
chunks = []
with open(self.file_path, 'rb') as f:
while True:
chunk = f.read(self.chunk_size)
if not chunk:
break
chunks.append(chunk)
return chunks
def read_file(self):
"""读取整个文件为二进制数据"""
with open(self.file_path, 'rb') as f:
return f.read()
def save_file(self, data, output_path=None):
"""保存数据到文件"""
if output_path is None:
output_path = self.file_path
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, 'wb') as f:
f.write(data)
return output_path
def get_file_info(self):
"""获取文件信息"""
if not os.path.exists(self.file_path):
return None
file_size = os.path.getsize(self.file_path)
file_hash = self.calculate_hash()
return {
'path': self.file_path,
'size': file_size,
'hash': file_hash,
'chunks_count': (file_size + self.chunk_size - 1) // self.chunk_size
}
def calculate_hash(self):
"""计算文件SHA256哈希值"""
sha256_hash = hashlib.sha256()
with open(self.file_path, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
@staticmethod
def combine_chunks(chunks):
"""合并数据块为完整文件"""
return b''.join(chunks)