Seek method supplement

The default mode of seek is to move the cursor from the beginning of the file, there are three modes of 0.1.2

 

f=open('seek.txt','r',encoding='utf-8')
print(f.tell())
f.seek( 10,0 ) #0 means move the cursor from the beginning of the file. This is the default
 print (f.tell())
f.seek(3,0)
print(f.tell())

 

 

f=open( ' seek.txt ' , ' rb ' ) #If you use other modes of seek , you must use b mode
 print (f.tell())
f.seek( 10,1)     # 1 represents the relative position, how to move this time relative to the last cursor 
print (f.tell())
f.seek(3,1)
print(f.tell())

 

f=open( ' seek.txt ' , ' rb ' ) #What's the use?  
print (f.tell())
f.seek( -5,2)       # 2 means move the cursor from the end of the file 
print (f.read()) #Read    is to read the content behind the cursor
 print (f.tell())
f=open( ' log file ' , ' rb ' )

for i in f.readlines(): #Using   readlines is to transfer all the content to the memory, which is equivalent to using a fishing net to get all the fish
     print (i)

#Recommended method of looping files
 for i in f:     #Use f to take the fish one by one, but here is to take one by one from the positive direction, and we have to take it from the back, so take it backwards and
     print (i)
 
 
f=open('log file','rb') #This part of the code means that you have a lot of logs, but you want to get the latest log, that is, how to operate the last line of log in your file
for i in f:
offs
=-10 while True: f.seek(offs, 2 ) #Read data from the end = f.readlines() if len(data) > 1 : #As long as the cursor position is above the last line, you can get the last line. If not, continue Increase the offs value print ( ' The last line of the file is %s ' %(data[-1].decode( ' utf-8 ' ))) break offs *=2

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325619017&siteId=291194637