以下是一个简单的 Python 替换模板脚本的示例:
```
import os
# 定义模板文件路径和目标文件路径
template_path = "path/to/template_file.txt"
target_path = "path/to/target_file.txt"
# 定义模板数据字典
data = {
"title": "替换模板脚本示例",
"content": "这是一个简单的替换模板脚本示例,用于给初学者提供参考。",
"author": "AI助手",
"date": "2021-11-11"
}
# 读取模板文件内容
with open(template_path, 'r') as template_file:
template_content = template_file.read()
# 使用字典中的数据替换模板文件
for key, value in data.items():
template_content = template_content.replace("{{" + key + "}}", value)
# 将替换后的内容写入目标文件
with open(target_path, 'w') as target_file:
target_file.write(template_content)
# 输出结果
print("替换完成!目标文件路径为:", target_path)
```
上述脚本的作用是,读取模板文件的内容,根据预先定义的数据字典,将其中的占位符(如`{{title}}`)替换为相应的实际值。然后将替换后的内容写入到目标文件中,完成替换过程。