Python_添加行号


 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)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM