Python reads the last line of the TXT file (file size + files small)

Source: Internet
Author: User

TXT file Small
 #coding: Utf-8 ' test.txt ' with Open (fname,  ' R ') as F:  #打开文件 lines = F.readlines ()  #读取所有行 First_line = lines[ 0]  #取第一行 last_line = Lines[-1]  #取最后一行 print  ' file ' + fname + " first behavior: ' + first_line print  ' file ' + fname +  Last behavior: ' + last_line            

When the file is very large, the use of this method is not feasible, the resources wasted too much, using the following scenario.

TXT file large
#coding: Utf-8"' F_name for the read Xx.txt file output is: The last line of the file" ' fname =' Test.txt 'With open (fname,' R ')As F:#打开文件 first_line = F.readline ()#读第一行 off =-50#设置偏移量Whiletrue:f.seek (off, 2)  #seek (off, 2) Represents the file pointer: Starting at the end of the file (2) forward 50 characters ( -50) lines = F.readlines ()  #读取文件指针范围内所有行 if len (lines) >= 2: # Determine if there are at least two lines at the end, so that the last line is complete last_line = Lines[-1]  #取最后一行 break  #如果off为50时得到的readlines只有一行内容, then there is no guarantee that the last line is complete  #所以off翻倍重新运行 until readlines more than one line off *= 2 print Span class= "hljs-string" > ' file ' + fname +  ' first behavior: ' + first_line  Print  ' file ' + fname +  Last behavior: ' + last_line    
Copyright NOTICE: This article is for bloggers original article, welcome reprint. Reprint please specify the source http://blog.csdn.net/binchasing

Python reads the last line of the TXT file (file size + files small)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.