Read the file (large file)

# Read file 
the try : 
    f = Open ( ' / path / to / File ' , ' r ' )
     Print (f.read ())
 a finally :
     IF f: 
        f.close () 


# simple wording 
with Open ( ' / path / to / file ' , ' r ' ) AS f:
     Print (f.read ()) 

' '' 
call to read () reads the contents of a file all at once, if the file has 10G, memory to burst, so, to be safe, you can call repeatedly read (size) method, each read up to size bytes of content. 

In addition, the call to readline () can read each line of text calling readlines () time to read all the contents and press OK to return list. Therefore, according to need to decide how you want to call.

If the file is small, read () reads a one-time most convenient; if you can not determine the file size, repeatedly calling read (size) safer; if it is the configuration file, call readlines () is most convenient: 

for Line in f.readlines () : 
    Print (line.strip ()) to the end of the # '\ n' delete 
'' ' 


' '' 
binary 
speaking in front of the default text file is read, and is UTF-8 encoded text file. To read a binary file, such as pictures, video, etc., to open the file 'rb' mode to: 

>>> F = Open ( '/ the Users / Michael / test.jpg', 'rb') 
>>> F. read () 
B '\ xFF \ xd8 \ xFF \ XE1 \ xOO \ x18Exif \ xOO \ ... xOO' represents the hexadecimal byte # 


character code 
to read a non-UTF-8 encoded text files, need to give open () function passing the encoding parameter, e.g., read GBK encoded files: 

>>> F = Open ( '/ the Users / Michael / gbk.txt', 'R & lt', encoding = 'GBK') 
>>> F .read () 
'test' 
'' '

 

Guess you like

Origin www.cnblogs.com/lvchengda/p/12614223.html