# -*- coding: utf-8 -*-

from pathlib import Path
from os import listdir
from os.path import isfile, join

# 获取脚本当前所在目录
current_dir = Path(__file__).parent.absolute()
print("current_dir: ", current_dir)

# 获取子目录，这里只是示例，实际没有用到
sub_dir = current_dir.joinpath("output")
print("sub_dir: ", sub_dir)

# 读取到的相关文件名保存在这个变量里
filenames = []
# 读取 current_dir 下所有目录及文件名
for filename in listdir(current_dir):
    # 使用当前所在目录+文件名，组成完整文件路径
    filename = join(current_dir, filename)
    # 检查是否是文件，并且以 '.html'结尾
    if isfile(filename) and filename.endswith(".html"):
        # 打印文件名
        print("filename: ", filename)
        # 写入到 filenames 里
        filenames.append(filename)

# 准备写入的文件
with open("merged.txt", 'w', encoding='utf-8') as f1:
    # 遍历前面读取到的文件名列表
    for filename in filenames:
        # 打开文件
        print("try open: ", filename)
        with open(filename, "r", encoding='utf-8') as f2:
            # 读取文件的内容
            content = f2.read()
            # 移除换行符
            content = content.replace("\r\n", "\n")
            content = content.replace("\n", "")
            # 写放文件
            f1.write(content + "\n</>\n")
