python創(chuàng)建模板文件及使用教程示例
寫作思路
1、模板的定義
2、如何利用模板生成多個文件
在很多情況下,我們會創(chuàng)建出很多樣式相似甚至是相同的類文件,比如在Android文件創(chuàng)建的時候(由于Android Studio已經(jīng)被我刪除很久了,就沒法實體展示)、Visual Studio創(chuàng)建繼承自虛方法的時候,創(chuàng)建出來的文件都已經(jīng)自帶了一些基礎(chǔ)格式和基礎(chǔ)方法
基于上述需求,有了利用模板類創(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é)果吧~
是不是很棒~當(dāng)然了,你可以根據(jù)模板根據(jù)需求定義更復(fù)雜的東西
以上就是python創(chuàng)建模板文件及使用教程示例的詳細(xì)內(nèi)容,更多關(guān)于python模板文件創(chuàng)建使用的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決pandas read_csv 讀取中文列標(biāo)題文件報錯的問題
今天小編就為大家分享一篇解決pandas read_csv 讀取中文列標(biāo)題文件報錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06Python 進(jìn)程操作之進(jìn)程間通過隊列共享數(shù)據(jù),隊列Queue簡單示例
這篇文章主要介紹了Python 進(jìn)程操作之進(jìn)程間通過隊列共享數(shù)據(jù),隊列Queue,結(jié)合實例形式分析了Python進(jìn)程數(shù)據(jù)共享、隊列數(shù)據(jù)處理相關(guān)操作技巧,需要的朋友可以參考下2019-10-10