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)+'
'   #添加行号
 9     lines[index]=newLine
10 with open(filename[:-3]+'_new.py','w')as fp:    #将结果写入文件
11     fp.writelines(lines)
原文地址:https://www.cnblogs.com/cmnz/p/6979307.html