在Python中:我需要带一个带有诗的文本文件并创建一个副本,但带有编号的行1,2。等

时间:2017-08-04 22:58:56

标签: python text lines numbered

我刚刚开始我只是不确定如何将数字放在每行的前面,因为它在txt文件中。这就是我到目前为止所拥有的。

def编号(infile,outfile):     对于infile线:         line =#我不知道从哪里开始

def main():

try:
    infileName = input("Enter the file holding the poem:")
    infile = open(infileName,"r")

    outfileName = input("Enter the file name to hold the numbered poem:")
    outfile = open(outfileName,"w")
    print("Numbered version of" + infileName + "is here in" + outfileName +)
except IOError:
    print ("Error, could not find files")

main()的

最终结果应该是 第一行的诗 第二行的诗 第三行诗 ECT

成: 1.第一首诗 第二行诗 3.第三行诗 ECT

1 个答案:

答案 0 :(得分:0)

我相信这会有所帮助:

poem = open('first.txt', 'r')
output = open('second.txt', 'w')
count = 1
for line in poem.readlines():
    output.write(str(count) + " " + line + "\n")
    count += 1
poem.close()
output.close()