python中获取文件行数的方法:
#获取文件行数
import os
os.chdir(r'C:\WorkDir\pyecharts-gallery-master\Bar3D')
os.listdir()
for count,line in enumerate(open(f"bar3d_base.py", "r", encoding='utf-8')):
count+=1
print(count)
在文件前部添加语句、删除文件尾部的最后两行,并记录倒数第2行,将其剪切到最后一行:
#对文件进行添头续尾
#添加到文件头的代码
strhost="""#LocalhostConfig
# 配置CurrentConfig.ONLINE_HOST为本机地址资源
from pyecharts.globals import CurrentConfig
CurrentConfig.ONLINE_HOST = "http://127.0.0.1:8000/assets/"
"""
import os
os.chdir(r'C:\WorkDir\pyecharts-gallery-master\Bar3D')
os.listdir()
filename='bar3d_base.py'
with open(filename, "r",encoding='utf-8') as fn:
strcode=fn.read()
print('----------origin file-----------')
print(strcode)
with open(filename, "r",encoding='utf-8') as oldf:
strold=oldf.readlines()
str_htmlrender=strold[-2].strip()#记录倒数第2行的html渲染程序
del strold[-1]#删除最后2行程序
del strold[-1]
with open(filename, "w",encoding='utf-8') as newf:
if not strcode.startswith("#LocalhostConfig"):#如果原代码前端还没有配置本地地址资源
newf.writelines(strhost)#首先在原代码的最前端添加本地地址资源
newf.writelines(strold)#接着添加原代码的内容
newf.writelines(')\nc.render_notebook()\nc')#然后添加在notebook中直接渲染的内容
newf.writelines(str_htmlrender)#最后将原来的渲染为html文件的内容添加在最后
with open(filename, "r",encoding='utf-8') as fn:
strcode=fn.read()
print('----------modify file-----------')
print(strcode)
最后实现的效果如下所示:
原始的python程序如下
自动进行修改后的python程序如下