Python修改文件往指定行插入內(nèi)容的實例
需求:批量修改py文件中的類屬性,為類增加一個core = True新的屬性
原py文件如下
a.py
class A(): description = "abc"
現(xiàn)在有一個1.txt文本,內(nèi)容如下,如果有py文件中的description跟txt文本中的一樣,則增加core屬性
1.txt
description = "abc" description = "123"
實現(xiàn)思路:
1.需要遍歷code目錄下的所有py文件,然后讀取所有行數(shù)內(nèi)容保存到lines列表中
2.遍歷每個文件的每一行,匹配1.txt中的description,如果匹配中,就返回行號
3.往lines列表中根據(jù)行號插入要增加的新屬性
4.重新寫回原文件,達到修改文件的目的
如果修改成功后,效果應(yīng)該是這樣的
a.py
class A(): description = "abc" core = True
實現(xiàn)代碼:
import os
original_folder = 'E:\\code\\'
core_list = []
count = 0
# if the description is in the current line
def isMatchDescription(line_buffer):
global core_list
# if not catch the core_list in global, reload it.
if not core_list:
with open("./core.txt","r") as f:
core_list = f.readlines()
# if match the core description
for des in core_list:
if line_buffer.strip() == des.strip():
return True
return False
def modifySignatures():
for dirpath, dirnames, filenames in os.walk(original_folder):
for filename in filenames:
modifyFile(os.path.join(dirpath,filename))
def modifyFile(filename):
global count
#print "Current file: %s"% filename
lines = []
with open(filename,"r") as f:
lines = f.readlines()
hit = 0
# Enume every single line for match the description
for index, line in enumerate(lines):
if isMatchDescription(line):
hit = index
print hit
print "Matched file:%s" % filename
count+=1
if hit > 0:
lines.insert(hit-1,' core = True\n')
f.close()
# Write back to file
with open(filename,"w") as f:
for line in lines:
f.write(line)
f.close()
if __name__ == '__main__':
modifySignatures()
print "Modified:%d"%count
代碼中的lines.insert(hit-1,' core = True\n')這一行,hit代表目標py文件的description屬性的行號,我之前用的是hit+1,但是后面發(fā)現(xiàn)有些文件出現(xiàn)了語法錯誤,原因是py文件中有些description的值太長,導(dǎo)致原文件使用了代碼換行符\,如下:
a.py
class A(): description = "abc\ aaaaabbbbb"
這樣的如果修改后就變成了
class A(): description = "abc\ core = True aaaaabbbbb"
為了避免這個bug,后面我才改成了hit-1
lines.insert(hit-1,' core = True\n')
這樣修改的py文件后就是這樣的效果
class A(): core = True description = "abc\ aaaaabbbbb"
以上這篇Python修改文件往指定行插入內(nèi)容的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python數(shù)據(jù)類型可變不可變知識點總結(jié)
在本篇文章里小編給各位整理的是關(guān)于python數(shù)據(jù)類型可變不可變知識點總結(jié),需要的朋友們可以學(xué)習(xí)下。2020-03-03
淺談python累加求和+奇偶數(shù)求和_break_continue
這篇文章主要介紹了淺談python累加求和+奇偶數(shù)求和_break_continue,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python編程實現(xiàn)微信企業(yè)號文本消息推送功能示例
這篇文章主要介紹了Python編程實現(xiàn)微信企業(yè)號文本消息推送功能,結(jié)合實例形式分析了Python微信企業(yè)號文本消息推送接口的調(diào)用相關(guān)操作技巧,需要的朋友可以參考下2017-08-08
詳解Python 中的 defaultdict 數(shù)據(jù)類型
這篇文章主要介紹了Python 中的 defaultdict 數(shù)據(jù)類型,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02
Python獲取當(dāng)前腳本文件夾(Script)的絕對路徑方法代碼
在本篇文章中小編給各位整理了關(guān)于Python獲取當(dāng)前腳本文件夾(Script)的絕對路徑實例代碼內(nèi)容,有需要的朋友們學(xué)習(xí)下。2019-08-08
selenium+python配置chrome瀏覽器的選項的實現(xiàn)
這篇文章主要介紹了selenium+python配置chrome瀏覽器的選項的實現(xiàn)。文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03

