python創(chuàng)建模板文件及使用教程示例
寫作思路
1、模板的定義
2、如何利用模板生成多個文件
在很多情況下,我們會創(chuàng)建出很多樣式相似甚至是相同的類文件,比如在Android文件創(chuàng)建的時候(由于Android Studio已經(jīng)被我刪除很久了,就沒法實體展示)、Visual Studio創(chuàng)建繼承自虛方法的時候,創(chuàng)建出來的文件都已經(jīng)自帶了一些基礎格式和基礎方法
基于上述需求,有了利用模板類創(chuàng)建文件的功能
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文件創(chuàng)建完成' % filename)
原理簡述:實際上就是一種字符串匹配以及字符串替代,你甚至可以自己寫一個匹配方式,然后用str.replace('${author}',author)來替換模板中的內(nèi)容!
運行結(jié)果
一開始文件的狀態(tài)如下

運行后的結(jié)果如下

然后再讓我們看看里面的生成結(jié)果吧~



是不是很棒~當然了,你可以根據(jù)模板根據(jù)需求定義更復雜的東西
以上就是python創(chuàng)建模板文件及使用教程示例的詳細內(nèi)容,更多關于python模板文件創(chuàng)建使用的資料請關注本站其它相關文章!
版權聲明:本站文章來源標注為YINGSOO的內(nèi)容版權均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。
關注官方微信