# ===== CodeLab: Python 文件与目录操作 =====
# 来源: https://aoerliang.dpdns.org/articles/python-file-io
# 以下代码片段按文章出现顺序拼接, 共 5 段

# ----- 片段 1 (python) -----
# 全部读入(适合小文件)
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(f"共 {len(content)} 个字符")

# 逐行处理(适合大文件,内存友好)
with open("data.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())   # strip 去掉行尾换行符

# 读所有行到列表
with open("data.txt", encoding="utf-8") as f:
    lines = f.readlines()
print(f"共 {len(lines)} 行")

# ----- 片段 2 (python) -----
# 覆盖写入
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("第一行\n")
    f.writelines(["第二行\n", "第三行\n"])

# 追加写入:保留原有内容
with open("out.txt", "a", encoding="utf-8") as f:
    f.write("追加的内容\n")

# 验证结果
with open("out.txt", encoding="utf-8") as f:
    print(f.read())

# ----- 片段 3 (python) -----
from pathlib import Path

p = Path("articles")
print(p.exists())
print(p.is_dir())
print(p.name)
print(p.parent)

# 路径拼接与后缀操作
q = Path("data") / "backup" / "report.txt"
print(q.suffix)
print(q.stem)
print(q.with_suffix(".csv"))

# ----- 片段 4 (python) -----
from pathlib import Path

# 当前目录下的所有 .py 文件(不递归)
for f in Path(".").glob("*.py"):
    print(f.name, f.stat().st_size, "字节")

# 递归查找所有 .md 文件
for f in Path(".").rglob("*.md"):
    print(f)

# 列出目录下所有条目
for item in Path(".").iterdir():
    kind = "目录" if item.is_dir() else "文件"
    print(f"[{kind}] {item.name}")

# ----- 片段 5 (python) -----
from pathlib import Path

src = Path("downloads")
if not src.exists():
    src.mkdir()   # 不存在则创建

# 预先建好几个分类目录
for folder in ["图片", "文档", "压缩包", "其他"]:
    (src / folder).mkdir(exist_ok=True)

# 按扩展名分类移动
for f in src.iterdir():
    if f.is_dir():
        continue   # 跳过目录本身
    ext = f.suffix.lower()
    if ext in (".jpg", ".png", ".gif"):
        dest = src / "图片"
    elif ext in (".pdf", ".docx", ".txt"):
        dest = src / "文档"
    elif ext in (".zip", ".tar", ".gz"):
        dest = src / "压缩包"
    else:
        dest = src / "其他"
    f.rename(dest / f.name)
    print(f"移动 {f.name} → {dest.name}/")

# 统计整理结果
for folder in src.iterdir():
    if folder.is_dir():
        count = len(list(folder.iterdir()))
        print(f"{folder.name}: {count} 个文件")
