码迷,mamicode.com
首页 > 编程语言 > 详细

Python_添加行号

时间:2017-06-10 18:15:21      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:rate   file   new   class   lin   with   写入文件   行号   遍历   

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

 

Python_添加行号

标签:rate   file   new   class   lin   with   写入文件   行号   遍历   

原文地址:http://www.cnblogs.com/cmnz/p/6979307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!