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)