Python-- file operations 2

File method tell (), seek (); file read, file write, file method flush (); file read and write, read-write file; binary file reading and writing

# Method Tell () Seek () 
# open files can read it, how to move the cursor for the next read operation 
F = Open ( " Yesterday " , ' R & lt ' , encoding = ' UTF-. 8 ' ) # file handle 
Print (F .tell ()) # print file pointer position 
Print (f.readline ())
 Print (f.readline ())
 Print (f.readline ())
 Print (f.tell ()) # number of characters 
# Tell () in accordance with the character count 
f.seek (0)
 Print (f.readline ()) # back to the first row 
# Tell () Seek () while using 

F = Open ( 'yesterday2 ' , ' W ' , encoding = ' UTF-. 8 ' ) 
f.write ( ' Hello. 1 \ n- ' ) 
f.write ( ' Hello 2 \ n- ' ) 
f.write ( ' Hello. 3 \ n- ' ) 
F. Write ( ' Hello. 4 \ n- ' ) 
f.write ( ' Hello. 5 \ n- ' ) 
f.write ( ' Hello. 6 \ n- ' ) 
f.close () 
# f.flush () updated in real time to the hard disk 
# the flush ( ) small application method: Print progress bar 
Import SYS, Time
for i in the Range (20 ): 
    sys.stdout.write ( " # " ) # stdout () standard output 
    sys.stdout.flush () 
    the time.sleep ( 0.1 )
 # file not only read but also write 
f = Open ( " yesterday2 " , ' R & lt + ' , encoding = ' UTF-. 8 ' ) # filehandle # r +: // write file open, read, write the end of the file then 
Print ( ' \ n- ' , f.readline ())
 Print ( f.readline ())
 Print (f.readline ()) 
f.write ( "hhhhhha ------------ ---------- " ) # write to the file, rather than the position of the cursor and then write 
Print (f.readline ()) 
f.close () 

F = Open ( " yesterday2 " , ' W + ' , encoding = ' UTF-. 8 ' ) # filehandle # w +: W R // no use 
f.write ( " --------- hhhhhhha-- ------------ \ the n- " ) 
f.write ( " --------- hhhhhhha -------------- \ the n- " ) 
f .write ( " --------- hhhhhhha -------------- \ the n- " ) 
f.write ( "hhhhhhha -------------- --------- \ the n- " ) 
f.write ( " --------- ------- hhhhhhha ------- \ the n- " ) 
f.write ( " --------- hhhhhhha -------------- \ the n- " ) 
f.write ( " - hhhhhhha -------------- -------- " ) 
f.close () 
# A +: no additional write common 

# reading binary file 
F = Open ( " yesterday2 " , ' rb ' ) # file handle // read in binary files 
Print (f.readline ())
 Print (f.readline ())
 Print (f.readline ())
 Print(f.readline ()) 
f.close () 
# binary file for network transmission 

# writing binary file 
F = Open ( " yesterday2 " , ' WB ' ) 
f.write ( " Hello binary \ n- " .encode ()) # encode () 
f.close ()

 

Guess you like

Origin www.cnblogs.com/zhaoxiaoxue/p/11183917.html