python创建模板文件及使用教程示例

时间:2021-09-12 02:27:52

写作思路

1、模板的定义
2、如何利用模板生成多个文件

在很多情况下,我们会创建出很多样式相似甚至是相同的类文件,比如在Android文件创建的时候(由于Android Studio已经被我删除很久了,就没法实体展示)、Visual Studio创建继承自虚方法的时候,创建出来的文件都已经自带了一些基础格式和基础方法
基于上述需求,有了利用模板类创建文件的功能

 

1、模板的定义

"""
  create in ${now}
  @author ${author}
"""
import sys
class ${ClassName}Class(object):
  def __init(self):
      pass
  def ${ClassName}GetData(self):
      pass
  def ${ClassName}SetData(self):
      pass
  def ${ClassName}Print(self, msg):
      print("${ClassName}", " print:", msg)
"""
  you can modify template from BaseClassTemplate.tpl
"""

看到上面那些 ${now}、 ${author}、 ${ClassName} 了吗!这些就是我们在模板中要替代的对象!

 

2、如何利用模板生成多个文件

import datetime
from string import Template
tplFilePath = r'F:\PythonXSLWorkSpace\TemplateGeneratePython\PythonTemplate\BaseClassTemplate.tpl'
path = r'F:\PythonXSLWorkSpace\TemplateGeneratePython\GenerateFloder\\'
ClassNameList = ["Game", "Music", "Live"]
for className in ClassNameList:
  now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  filename = className + 'Class.py'
  author = '在逆境中蜕变'
  tplFile = open(tplFilePath)
  gFile = open(path + filename, "w")
  lines = []
  tpl = Template(tplFile.read())
  lines.append(tpl.substitute(
      author=author,
      now=now,
      ClassName=className))
  gFile.writelines(lines)
  tplFile.close()
  gFile.close()
  print('%s文件创建完成' % filename)

原理简述:实际上就是一种字符串匹配以及字符串替代,你甚至可以自己写一个匹配方式,然后用str.replace('${author}',author)来替换模板中的内容!

 

运行结果

一开始文件的状态如下

python创建模板文件及使用教程示例

运行后的结果如下

python创建模板文件及使用教程示例

然后再让我们看看里面的生成结果吧~

python创建模板文件及使用教程示例

python创建模板文件及使用教程示例

python创建模板文件及使用教程示例

是不是很棒~当然了,你可以根据模板根据需求定义更复杂的东西

以上就是python创建模板文件及使用教程示例的详细内容,更多关于python模板文件创建使用的资料请关注服务器之家其它相关文章!

原文链接:https://blog.csdn.net/weixin_40301728/article/details/110203259