python 模板文件的创建及使用

写作思路

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 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) ``` 上述代码中,我们使用了一个模板文件`BaseClassTemplate.tpl`作为文件内容的模板模板使用了`${now}`、`${author}`和`${ClassName}`作为占位符。在循环遍历类名列表时,我们使用`Template`类的`substitute`方法替换了占位符,并将替换后的内容写入目标文件中。 模板文件的内容如下所示: ```python """ 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}`作为占位符,可以根据实际情况进行替换。 通过上述代码,我们可以创建多个文件,并且根据模板生成文件内容。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [python 模板文件创建使用](https://blog.csdn.net/weixin_40301728/article/details/110203259)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [shell命令行,一键创建 python 模板文件脚本方法](https://download.csdn.net/download/weixin_38736721/13773353)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值