品易云推流 关闭
文章详情页
文章 > Python常见问题 > 在python中如何加入行号?

在python中如何加入行号?

头像

yang

2020-05-05 09:50:125170浏览 · 0收藏 · 0评论

python添加行号:

 filename='demo.py'
 with open(filename,'r')as fp:
     lines=fp.readlines() #读取所有行
 maxLength=max(map(len,lines))   #最长行的长度
 for index,line in enumerate(lines): #遍历所有行
     newLine=line.rstrip()   #删除每行右侧的空白字符
     newLine=newLine+' '*(maxLength+5-len(newLine))  #在每行固定位置添加行号
     newLine=newLine+'#'+str(index+1)+'\n'   #添加行号
     lines[index]=newLine
 with open(filename[:-3]+'_new.py','w')as fp:    #将结果写入文件
     fp.writelines(lines)

readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for... in ... 结构进行处理。

更多Python知识请关注Python视频教程栏目。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图