python 怎样或读取一个文件的最后一行

python 怎样或读取一个文件的最后一行,第1张

有两种情况,

1,文件比较大时,一行一行循环直到最后一行,读取最后一行;

targetLine = ""

lineNo = 0  

while 1:

    mLine = file.readline()

    if not mLine:

        break

    lineNo += 1

    if (linecount == lineNO):

        targetLine = mLine

2, 文件比较小,直接读取全文,取最后一行数据。

targetLine = ""  

mLines = file.read()

targetLine = mLines[-1] filelineno( ) 

Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file.

如下的回答请参考:

1、导入模块

import xlrd

2、打开Excel文件读取数据

data = xlrd.open_workbook('excelFile.xls')

3、使用技巧

获取一个工作表

table = data.sheets()[0] #通过索引顺序获取

table = data.sheet_by_index(0) #通过索引顺序获取

table = data.sheet_by_name(u'Sheet1')#通过名称获取

可以采用这样的方法:

f=open('data2.txt')

print(''.join(f.readlines()[-1]))

如果文件很大,考虑到内存的问题,也可以用如下方法:

f=open('data2.txt')

for a in f:

pass

f.close()

print(a)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/10020960.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-04
下一篇 2023-05-04

发表评论

登录后才能评论

评论列表(0条)

保存