在python中如何加入行号?

图片[1]-在python中如何加入行号?-uusu优素-乐高,模型,3d打印,编程

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
喜欢就支持一下吧
点赞14 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容