这种读取文本文件中最后一行的方式是不正确的?蟒蛇

时间:2013-11-27 20:16:01

标签: python file io

我试图读取文本文件的最后一行,所以我想出了这个 这是不正确的吗?

import time
Data = open("Data.txt")
lines = len(Data.readlines())
Data.close() 

print lines

Data = open("Data.txt")

for x in range(0, lines):
    lastline = Data.readline()
#   print lastline


print lastline

1 个答案:

答案 0 :(得分:4)

从句法上来说,我没有看到代码有什么问题,但它可以做得更简单。使用with是打开文件的建议方式,它确保在代码退出with的范围后正确关闭文件,从而简化代码。

with open("Data.txt") as f:
    # readlines returns a list of lines in the file
    # since it is a list all you need do is access the last element in the list
    # that element should be the last line in your text file.
    last_line = f.readlines()[-1] 

    print last_line