Copy the last three lines of a text file in python?

前端 未结 5 1781
故里飘歌
故里飘歌 2020-12-17 03:40

I\'m new to python and the way it handles variables and arrays of variables in lists is quite alien to me. I would normally read a text file into a vector and then copy the

5条回答
  •  鱼传尺愫
    2020-12-17 03:57

    First to answer your question, my guress is that you had an index error you should replace the line writeLine[i] with writeLine.append( ). After that, you should also do a loop to write the output :

    text_file = open("Output.txt", "w")
    for row in writeLine :
        text_file.write(row)
    text_file.close()
    

    May I suggest a more pythonic way to write this ? It would be as follow :

    with open("Input.txt") as f_in, open("Output.txt", "w") as f_out :
        for row in f_in.readlines()[-3:] :
            f_out.write(row)
    

提交回复
热议问题