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

时间:2014-02-23 22:19:40

标签: python python-2.7

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

"This is record #1"
"This is record #2"
"This is record #3"

我需要以下格式输出:

Line number (1) --\t-- "This is Record # 1"
2-- \t-- "This is Record # 2"
3-- \t-- "This is Record # 3" 

当前代码:

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()

2 个答案:

答案 0 :(得分:5)

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

f = open('workfile', 'r')
for num,line in enumerate(f):
    print(num+" "+line)

答案 1 :(得分:2)

您的代码非常接近目标:

# open the file for reading
f = open("C:\input.txt","r")

# and a file for writing
write_file = open("C:\output.txt","r+")

for i, line in enumerate(f):
    line = f.readline()
    mod_line = "%s-- \t-- %s" % (i, line)  # 1-- \t-- "This is Record # 1"
    write_file.write(mod_line)

write_file.close()
f.close()