python文件读取到最后一行后怎么返回第一行
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python文件读取到最后一行后怎么返回第一行相关的知识,希望对你有一定的参考价值。
参考技术A file= open('files.txt')file.seek(0)
python 怎样或读取一个文件的最后一行
有没有简便的方法,获取文件的行数
我用了这个方法,
import os
file = open('abc.dat','r')
linecount = len(file.readlines());
targetLine = "";
lineNo = 0;
while 1:
mLine = file.readline();
if not mLine:
break;
lineNo += 1;
if (linecount == lineNO):
targetLine = mLine;
但是最后发现targetLine里面是空的
有两种情况,
1,文件比较大时,一行一行循环直到最后一行,读取最后一行;
lineNo = 0;
while 1:
mLine = file.readline();
if not mLine:
break;
lineNo += 1;
if (linecount == lineNO):
targetLine = mLine;
2, 文件比较小,直接读取全文,取最后一行数据。
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.
参考技术A 有两种情况,
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.本回答被提问者采纳
以上是关于python文件读取到最后一行后怎么返回第一行的主要内容,如果未能解决你的问题,请参考以下文章