在python中将行号前置为字符串

use*_*672 2 python python-2.7

我有一个以下格式的文本文件:

"This is record #1"
"This is record #2"
"This is record #3"
Run Code Online (Sandbox Code Playgroud)

我需要以下格式的输出:

Line number (1) --\t-- "This is Record # 1"
2-- \t-- "This is Record # 2"
3-- \t-- "This is Record # 3" 
Run Code Online (Sandbox Code Playgroud)

当前代码:

f = open("C:\input.txt","r")
write_file = open("C:\output.txt","r+")
while True:
    line = f.readline()
    write_file.write(line)
    if not line : break
write_file.close()
f.close()
Run Code Online (Sandbox Code Playgroud)

cru*_*nch 5

尝试以这种方式遍历您的文件:

f = open('workfile', 'r')
for num,line in enumerate(f):
    print(num+" "+line)
Run Code Online (Sandbox Code Playgroud)

  • 这将计数从0开始,而不是1.给`enumerate()`第二个参数:`enumerate(f,1)`从1开始. (4认同)