黑松山资源网 Design By www.paidiu.com
需求:批量修改py文件中的类属性,为类增加一个core = True新的属性
原py文件如下
a.py
class A(): description = "abc"
现在有一个1.txt文本,内容如下,如果有py文件中的description跟txt文本中的一样,则增加core属性
1.txt
description = "abc" description = "123"
实现思路:
1.需要遍历code目录下的所有py文件,然后读取所有行数内容保存到lines列表中
2.遍历每个文件的每一行,匹配1.txt中的description,如果匹配中,就返回行号
3.往lines列表中根据行号插入要增加的新属性
4.重新写回原文件,达到修改文件的目的
如果修改成功后,效果应该是这样的
a.py
class A(): description = "abc" core = True
实现代码:
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,但是后面发现有些文件出现了语法错误,原因是py文件中有些description的值太长,导致原文件使用了代码换行符\,如下:
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修改文件往指定行插入内容的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月07日
2024年10月07日
- 群星.1991-音乐工厂1·皇后大道东【音乐工厂】【WAV+CUE】
- 群星.1992-音乐工厂2·首都【音乐工厂】【WAV+CUE】
- 群星.1994-音乐工厂3·儿童乐园【音乐工厂】【WAV+CUE】
- 胡鸿钧.2021-ex:CHANGE【星梦娱乐】【WAV+CUE】
- 班得瑞原装进口《第一张新世纪专辑:仙境》1CD[APE/CUE分轨][292.3MB]
- 伍佰《摇滚教父 伍佰黄金精选 2CD》[WAV+CUE][990MB]
- 班得瑞原装进口《第二张新世纪专辑:寂静山林》1CD[APE/CUE分轨][327.1MB]
- Beyond.1989-真的见证(2024环球MQA-UHQCD限量版)【环球】【WAV+CUE】
- 陈怡婷.2024-予你的心谁来赔【福茂】【FLAC分轨】
- 陈冠希.2003-HITS.OR.MISSES【英皇娱乐】【WAV+CUE】
- 班得瑞原装进口《第三张新世纪专辑:春野》1CD[APE/CUE分轨][278.9MB]
- 班得瑞原装进口《第四张新世纪专辑:蓝色天际》1CD[APE/CUE分轨][284.8MB]
- 班得瑞原装进口《第五张新世纪专辑:迷雾森林+EP》1CD[APE/CUE分轨][334.2MB]
- 田震.1997-顺其自然(日版)【红星生产社】【WAV+CUE】
- 小虫.1996-想得太美【滚石】【WAV+CUE】