Python修改文件往指定行插入内容的实例修改文件往指定行插入内容的实例
今天小编就为大家分享一篇Python修改文件往指定行插入内容的实例,具有很好的参考价值,希望对大家有所
帮助。一起跟随小编过来看看吧
需求:需求:批量修改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
评论0