2014-02-23 51 views
2

字符串我有以下格式的文本文件:前面加上行號在Python

"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() 
+0

順便說一句,這將是_prepending_的行號。 –

+1

我很抱歉把它寫錯了。 – user3339672

回答

5

嘗試以下列方式遍歷文件:

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

這從0開始計數,而不是1.給'enumerate()'第二個參數:'enumerate(f,1)'從1開始。 –

+0

我根據你的答案和所有建議修改了代碼,如下所示:對於num,枚舉中的行(f,1): write_file.write(str(num)+「\ t」+ line)。謝謝您的幫助。欣賞它。 – user3339672

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

非常感謝您的幫助。感謝你的幫助。 – user3339672

+0

如果你感謝它,請投票回答 – tutuDajuju

+2

我很樂意,但每當我嘗試這樣做,它說至少需要15聲望。也許因爲我是新的。再次感謝。 – user3339672