\db_path style

This commit is contained in:
Burgess Leo
2025-05-22 17:21:44 +08:00
parent 3347abe02f
commit d2a3a7b5b5
9 changed files with 301 additions and 111 deletions

View File

@@ -27,23 +27,23 @@ def ScanVolume(volume_letter: str):
"""
完整扫描指定磁盘的所有文件和目录,忽略 NTFS 元文件和系统文件夹,
并为每个节点分配 ParentID。
返回:
list of dict包含文件/目录信息的字典列表
"""
root_path = f"{volume_letter.upper()}:\\"
if not os.path.exists(root_path):
raise ValueError(f"磁盘 {root_path} 不存在")
result = []
path_to_id = {} # 用于记录路径到数据库 ID 映射
counter = 1 # 模拟数据库自增 ID
path_to_id = {} # 路径 -> ID 映射
counter = 1
for root, dirs, files in os.walk(root_path, topdown=True, onerror=None, followlinks=False):
# 过滤掉需要跳过的目录
dirs[:] = [d for d in dirs if not ShouldSkipPath(os.path.join(root, d))]
for entry in files + dirs:
entries = files + dirs
for entry in entries:
full_path = os.path.join(root, entry)
if ShouldSkipPath(full_path):
@@ -61,21 +61,35 @@ def ScanVolume(volume_letter: str):
name = entry
# ✅ 修正点:对 Path 字段进行哈希
path_hash = GenerateHash(full_path)
# 分离盘符并去除开头的 \
_, relative_path = os.path.splitdrive(full_path)
relative_path = relative_path.lstrip("\\")
# 如果是文件夹Path 字段结尾加 '\\'
if is_dir and not relative_path.endswith("\\"):
relative_path += "\\"
# ✅ 关键修改点:将所有 \ 替换为 \\
relative_path = relative_path.replace("\\", "\\\\")
path_hash = GenerateHash(relative_path)
# 计算 ContentSizeKB小文件至少显示为 1 KB
content_size = bytes_size // 1024
if content_size == 0 and bytes_size > 0:
content_size = 1
# 获取父目录路径
parent_path = os.path.dirname(full_path)
parent_id = path_to_id.get(parent_path, 0) # 默认为 0根目录可能未录入
_, parent_relative_path = os.path.splitdrive(parent_path)
parent_relative_path = parent_relative_path.lstrip("\\").rstrip("\\") # 去除首尾 \
if os.path.isdir(parent_path) and not parent_relative_path.endswith("\\"): # 如果是目录,补 \
parent_relative_path += "\\"
parent_relative_path = parent_relative_path.replace("\\", "\\\\") # 转换为双反斜杠 \\
parent_id = path_to_id.get(parent_relative_path, 0)
item = {
"ID": counter,
"Path": full_path,
"Path": relative_path,
"Name": name,
"PathHash": path_hash,
"IsDir": is_dir,
@@ -84,7 +98,7 @@ def ScanVolume(volume_letter: str):
}
result.append(item)
path_to_id[full_path] = counter
path_to_id[relative_path] = counter
counter += 1
except Exception as e:
@@ -163,7 +177,7 @@ def InsertPathDataToDB(data, db_path='../src/db_ntfs_info.db', table_name='db_pa
# 示例主函数
def main():
volume_letter = "Z"
volume_letter = "Y"
print(f"🔍 开始全盘扫描磁盘 {volume_letter}:\\ ...")
scanned_data = ScanVolume(volume_letter)