-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
68 lines (55 loc) · 2.13 KB
/
data.py
File metadata and controls
68 lines (55 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import os, re, json, ctypes
from pathlib import Path
from functools import cmp_to_key
# ========= 排序逻辑 =========
if os.name == "nt":
_strcmp = ctypes.windll.shlwapi.StrCmpLogicalW
_strcmp.argtypes, _strcmp.restype = [ctypes.c_wchar_p, ctypes.c_wchar_p], ctypes.c_int
def _cmp_name(a, b): return _strcmp(str(a), str(b))
else:
def _alphanum_key(s): return [int(x) if x.isdigit() else x.lower() for x in re.split(r'(\d+)', s)]
def _cmp_name(a, b):
ka, kb = _alphanum_key(a), _alphanum_key(b)
return (ka > kb) - (ka < kb)
# ========= 树构建 =========
def safe_stat(path):
try:
return os.stat(path, follow_symlinks=False)
except Exception:
return None
def scan_tree(path):
"""扫描目录并返回 [name, size或children, mtime]"""
if os.path.islink(path):
return None
st = safe_stat(path)
if not st:
return None
name = Path(path).name
if os.path.isdir(path):
try:
entries = os.listdir(path)
except OSError:
return [name, [], int(st.st_mtime)]
def cmp_entry(a, b):
a_path, b_path = os.path.join(path, a), os.path.join(path, b)
a_isdir, b_isdir = os.path.isdir(a_path), os.path.isdir(b_path)
return -1 if a_isdir and not b_isdir else 1 if b_isdir and not a_isdir else _cmp_name(a, b)
children = filter(None, (scan_tree(os.path.join(path, e)) for e in sorted(entries, key=cmp_to_key(cmp_entry))))
return [name, list(children), int(st.st_mtime)]
else:
return [name, st.st_size, int(st.st_mtime)]
# ========= 主函数 =========
def main():
root = "d"
if not os.path.exists(root):
print(f"Error: The directory '{root}' does not exist")
return
print("Scanning directory, please wait...")
tree = scan_tree(root)
if tree: tree[0] = "" # 根名置空
Path("static").mkdir(exist_ok=True)
with open("static/data.json", "w", encoding="utf-8") as f:
json.dump(tree, f, ensure_ascii=False, separators=(",", ":"))
print("Data has been exported to static/data.json")
if __name__ == "__main__":
main()