• 技术文章 >常见问题 >Python常见问题

    在python中如何加入行号?

    yangyang2020-05-05 09:50:12原创4437

    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视频教程栏目。

    专题推荐:python
    品易云
    上一篇:java与python哪个运行快? 下一篇:在python里int是什么意思

    相关文章推荐

    • 怎么判断python的版本号• python如何判断是不是汉字?• python如何使用命令关机• python脚本查找文件是否存在的方法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网