[英]Python print number lines and line from text file
Im trying to read lines from a text file and print the number of the line and the line next to the number我试图从文本文件中读取行并打印行号和数字旁边的行
Ive tried using enumerate but I want to find another way of doing it我试过使用 enumerate 但我想找到另一种方法
the file contains :该文件包含:
pizza hello goodbye
I want to print to the screen我想打印到屏幕上
1-pizza 2-hello 3-goodbye
a simple for loop over the file:一个简单的 for 循环文件:
lineCounter=0
with open('C:/t.txt') as readObj:
lines=readObj.readlines()
for line in lines:
line=line.rstrip('\n')
lineCounter += 1
print('{}-{}'.format(lineCounter,line))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.