"""1. Three ways to read the file: Read (), ReadLine (), ReadLines () 2, three methods all accept a variable to limit the amount of data that is read each time, and typically do not use the variable. """"""about the Read () method: 1, read the entire file, put the contents of the file into a string variable 2, if the file is larger than the available memory, it is not possible to use this processing"""File_object= Open ("test.py",'R')#creates a file object and is also an object that can be iterated overTry: All_the_text= File_object.read ()#The result is a str type Printtype (all_the_text)Print "all_the_text=", All_the_textfinally: File_object.close ()"""about ReadLine () method: 1, ReadLine () reads one line at a time, is much slower than ReadLines () 2, ReadLine () returns a string object that holds the contents of the current row"""File_object1= Open ("test.py",'R')Try: whileTrue:line=File_object1.readline ()ifLine :Print "line=", LineElse: Breakfinally: File_object1.close ()"""about ReadLines () method: 1, read the entire file at once. 2, automatically analyze the contents of the file into a list of rows. """File_object2= Open ("test.py",'R')Try: Lines=File_object2.readlines ()Print "type (lines) =", type (lines)#type (lines) = <type ' list ' > forLineinchlines:Print "line=", Linefinally: File_object2.close ()
Three ways Python reads a file read (), ReadLine (), ReadLines ()