python添加行号:
filename='demo.py' withopen(filename,'r')asfp: lines=fp.readlines()#读取所有行 maxLength=max(map(len,lines))#最长行的长度 forindex,lineinenumerate(lines):#遍历所有行 newLine=line.rstrip()#删除每行右侧的空白字符 newLine=newLine+''*(maxLength+5-len(newLine))#在每行固定位置添加行号 newLine=newLine+'#'+str(index+1)+'\n'#添加行号 lines[index]=newLine withopen(filename[:-3]+'_new.py','w')asfp:#将结果写入文件 fp.writelines(lines)
readlines()方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for… in … 结构进行处理。
原文来自:https://www.py.cn© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容