簡體   English   中英

Python 從文本文件中打印數字行和行

[英]Python print number lines and line from text file

我試圖從文本文件中讀取行並打印行號和數字旁邊的行

我試過使用 enumerate 但我想找到另一種方法

該文件包含:

pizza
hello
goodbye

我想打印到屏幕上

1-pizza
2-hello
3-goodbye

一個簡單的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM