国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python修改文件往指定行插入內(nèi)容的實(shí)例

2020-02-16 01:00:46
字體:
供稿:網(wǎng)友

需求:批量修改py文件中的類屬性,為類增加一個(gè)core = True新的屬性

原py文件如下

a.py

class A():  description = "abc"

現(xiàn)在有一個(gè)1.txt文本,內(nèi)容如下,如果有py文件中的description跟txt文本中的一樣,則增加core屬性

1.txt

description = "abc"description = "123"

實(shí)現(xiàn)思路:

1.需要遍歷code目錄下的所有py文件,然后讀取所有行數(shù)內(nèi)容保存到lines列表中

2.遍歷每個(gè)文件的每一行,匹配1.txt中的description,如果匹配中,就返回行號(hào)

3.往lines列表中根據(jù)行號(hào)插入要增加的新屬性

4.重新寫回原文件,達(dá)到修改文件的目的

如果修改成功后,效果應(yīng)該是這樣的

a.py

class A():  description = "abc"  core = True

實(shí)現(xiàn)代碼:

import osoriginal_folder = 'E://code//'core_list = []count = 0# if the description is in the current linedef 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 Falsedef 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代表目標(biāo)py文件的description屬性的行號(hào),我之前用的是hit+1,但是后面發(fā)現(xiàn)有些文件出現(xiàn)了語法錯(cuò)誤,原因是py文件中有些description的值太長(zhǎng),導(dǎo)致原文件使用了代碼換行符/,如下:

a.py

class A():  description = "abc/  aaaaabbbbb"

這樣的如果修改后就變成了

class A():  description = "abc/  core = True  aaaaabbbbb"

為了避免這個(gè)bug,后面我才改成了hit-1

lines.insert(hit-1,' core = True/n')

這樣修改的py文件后就是這樣的效果

class A():  core = True  description = "abc/  aaaaabbbbb"
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 邻水| 咸阳市| 喀喇沁旗| 阜宁县| 望江县| 广宁县| 房山区| 台南县| 元朗区| 东乌珠穆沁旗| 孝义市| 察哈| 安徽省| 龙陵县| 义乌市| 普宁市| 大安市| 环江| 桂林市| 尉氏县| 饶河县| 安康市| 鸡西市| 安龙县| 娱乐| 潞城市| 宝应县| 东丽区| 苗栗市| 博野县| 揭东县| 和硕县| 南和县| 丽江市| 奎屯市| 阳城县| 凤翔县| 千阳县| 龙井市| 唐河县| 邵东县|