The method of three read python file read (), readline (), readlines () Explanation

"" "
Three methods 1 to read the file: Read (), the readline (), the readlines ()
2, three methods can be acceptable to limit the amount of data each time a read is variable, the variable is normally not used .
"" "

"" "
On read () method:
1, read the entire file, the file contents into a string variable
2, if the file is larger than the available memory, it is impossible to use this process
", ""
the file_object = Open ( "Test. py ", 'r') # create a file object, is also an iterable
the try:
all_the_text = file_object.read () # result is str type
Print of the type (all_the_text)
Print" all_the_text = ", all_the_text
a finally:
file_object.close ( )

"" "
On the readline () method:
. 1, the readline () reads each line, the readlines ratio () much slower
2, readline () returns a string object, to save the contents of the current line
" ""
file_object1 = Open ( "the test.py", 'R & lt')
the try:
the while True:
Line = file_object1.readline ()
IF Line:
Print "Line =", Line
the else:
BREAK
the finally:
file_object1.close ()

"" "
On the readlines () Method:
1, a one-time read the entire file.
2, the contents of the file automatically into a list row. "
""
File_object2 = Open ( "the test.py ',' R & lt ')
the try:
= file_object2.readlines Lines ()
Print "type (Lines) =", type (Lines) #type (Lines) = <type 'List'>
for in Lines Line:
Print "Line =", Line
the finally:
file_object2.close ( )

Guess you like

Origin www.cnblogs.com/yangyangming/p/10961876.html