74 lines
2.4 KiB
Python
74 lines
2.4 KiB
Python
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)}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
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")
|