当前位置: 首页 > 图灵资讯 > 行业资讯> 在python中如何加入行号?

在python中如何加入行号?

发布时间:2026-05-02 09:59:36

python添加行号:

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

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

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

相关文章

用python如何判断字符的大小写

用python如何判断字符的大小写

2026-05-29
python日志怎么存储

python日志怎么存储

2026-05-11
python能开发前端吗

python能开发前端吗

2026-05-11
python如何汇总多个excel

python如何汇总多个excel

2026-05-11
如何利用python快速生成大文件

如何利用python快速生成大文件

2026-05-11
怎么判断Python数字中的偶数

怎么判断Python数字中的偶数

2026-05-11