finish copy files follow bytes sort

This commit is contained in:
Burgess Leo
2025-05-22 09:16:37 +08:00
parent cd536a6bd3
commit 0c98dfecda
7 changed files with 566 additions and 47 deletions

72
test/files_save.py Normal file
View File

@@ -0,0 +1,72 @@
import os
def extract_drive_letter(path: str) -> str:
"""从绝对路径中提取盘符"""
drive = os.path.splitdrive(path)[0]
if not drive:
raise ValueError(f"无法从路径中提取盘符:{path}")
return drive[0].upper() # 返回 'Y'
def CopyFileFromBytes(source_data_dict, target_path):
"""
根据起始字节和长度,从磁盘中读取数据并保存为目标文件
:param source_data_dict: 包含源数据信息的字典
:param target_path: 目标文件夹路径
"""
start_byte = source_data_dict.get("start_byte")
byte_length = source_data_dict.get("length")
absolute_path = source_data_dict.get("absolute_path")
file_name = source_data_dict.get("filename")
if byte_length <= 0:
print("错误:字节长度无效")
return
if not absolute_path or not file_name:
print("错误:缺少必要的文件信息")
return
source_disk_path = extract_drive_letter(absolute_path)
target_file_path = os.path.join(target_path, file_name)
try:
# 创建目标目录(如果不存在)
os.makedirs(target_path, exist_ok=True)
with open(fr"\\.\{source_disk_path}:", 'rb') as disk:
disk.seek(start_byte)
with open(target_file_path, 'wb') as f:
remaining = byte_length
CHUNK_SIZE = 1024 * 1024 # 1MB
while remaining > 0:
read_size = min(CHUNK_SIZE, remaining)
chunk = disk.read(read_size)
if not chunk:
print("警告:读取到空数据,可能已到达磁盘末尾。")
break
f.write(chunk)
remaining -= len(chunk)
print(
f"成功:已从字节偏移量 {start_byte} 读取 {byte_length} 字节,保存为 {target_file_path}")
except PermissionError:
print("错误:需要管理员权限访问磁盘设备,请以管理员身份运行此程序")
except Exception as e:
print(f"发生错误: {str(e)}")
test_dict = {
'absolute_path': 'Y:\\CloudMusic\\Aaron Zigman - Main Title.mp3',
'filename': 'Aaron Zigman - Main Title.mp3',
'extent_count': 1,
'start_byte': 687685632,
'length': 7163904,
'fragment_index': 1
}
CopyFileFromBytes(test_dict, target_path=r"Z:\RecoveredFiles")