首页 > 编程知识 正文

python取文件最后几行,python提取前几行数据

时间:2023-12-29 13:16:39 阅读:329923 作者:JINI

本文目录一览:

python 怎么读取文件每行的开头和末尾?

text="""

16 wyp1 23 131212121212

17 wyp2 24 134535353535

18 wyp3 25 132453535353

19 wyp4 26 154243434355

20 wyp 25 13188888888888

21 test 30 13888888888888

22 zs 34 899314121

"""

text_arr = text.split("n")#根据换行符拆分字符串

# print(text_arr)

#content_dict = {}#字典,用来装结果

for i in text_arr:

if i == "":#如果这个内容是空的,则略过,继续下一个

continue

i_arr = i.split(" ")#根据空格拆分字符串

content_dict[i_arr[0]] = i_arr[-1]#将字符串列表的第一个位置作为键,最后一个位置的内容作为值

print(content_dict)

两次print的结果

ps:图片好像不是高清的.......

如何用python最快的获取大文件的最后几行

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

#!/usr/bin/env python

import os

import sys

def get_last_n_lines(logfile, n):

blk_size_max = 4096

n_lines = []

with open(logfile, 'rb') as fp:

fp.seek(0, os.SEEK_END)

cur_pos = fp.tell()

while cur_pos 0 and len(n_lines) n:

blk_size = min(blk_size_max, cur_pos)

fp.seek(cur_pos - blk_size, os.SEEK_SET)

blk_data = fp.read(blk_size)

assert len(blk_data) == blk_size

lines = blk_data.split('n')

# adjust cur_pos

if len(lines) 1 and len(lines[0]) 0:

n_lines[0:0] = lines[1:]

cur_pos -= (blk_size - len(lines[0]))

else:

n_lines[0:0] = lines

cur_pos -= blk_size

fp.seek(cur_pos, os.SEEK_SET)

if len(n_lines) 0 and len(n_lines[-1]) == 0:

del n_lines[-1]

return n_lines[-n:]

def main():

if len(sys.argv) != 3:

sys.exit('usage: %s logfile n_lines' % sys.argv[0])

for line in get_last_n_lines(sys.argv[1], int(sys.argv[2])):

print line

if __name__ == '__main__':

main()

Linux平台有一个tail命令,tail -f filename.log 就会打印文件最后新增加的内容

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

有两种情况,

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获取文件的最后一行,文件可能会比较大

#!/usr/bin/env python

import os

import sys

def get_last_n_lines(logfile, n):

    blk_size_max = 4096

    n_lines = []

    with open(logfile, 'rb') as fp:

        fp.seek(0, os.SEEK_END)

        cur_pos = fp.tell()

        while cur_pos  0 and len(n_lines)  n:

            blk_size = min(blk_size_max, cur_pos)

            fp.seek(cur_pos - blk_size, os.SEEK_SET)

            blk_data = fp.read(blk_size)

            assert len(blk_data) == blk_size

            lines = blk_data.split('n')

            # adjust cur_pos

            if len(lines)  1 and len(lines[0])  0:

                n_lines[0:0] = lines[1:]

                cur_pos -= (blk_size - len(lines[0]))

            else:

                n_lines[0:0] = lines

                cur_pos -= blk_size

            fp.seek(cur_pos, os.SEEK_SET)

    if len(n_lines)  0 and len(n_lines[-1]) == 0:

        del n_lines[-1]

    return n_lines[-n:]

def main():

    if len(sys.argv) != 3:

        sys.exit('usage: %s logfile n_lines' % sys.argv[0])

    for line in get_last_n_lines(sys.argv[1], int(sys.argv[2])):

        print line

if __name__ == '__main__':

    main()

Linux平台有一个tail命令,tail -f filename.log 就会打印文件最后新增加的内容

 

这个也可以

如何利用python读取特定目录下的特定文件的倒数两行

读取最后2行,别信那些用readlines()的答案。那些答案,丢给你个16GB的文件就死翘翘了。老老实实用tail命令的实现方法:

用os.seek跳转到文件末尾,os.tell判断文件大小

设置个合适的buf size,假设是1024。循环从文件末尾os.seek往回跳buf size,判断读取的内容里回车符的数量,累加回车符数量

当回车符数量大于等于2的时候,停止循环。确定倒数第二个回车符的位置,os.seek到那个位置,输出到文件末尾

这个实现还是有坑。如果文件一直在增长,那么『最后两行』应该是程序执行当时文件的最后两行,步骤3里应该是『从倒数第二个回车符输出到步骤1中获取的文件大小位置』

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。