The contents of the file Runoob.txt are as follows:
1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com
To iterate through the contents of a file:
#!/usr/bin/python#-*-coding:utf-8-*-#Open FileFO = open ("Runoob.txt","rw+")Print "the file name is:", Fo.nameline=Fo.readline ()Print "read the first line of%s"%(line)= Fo.readline (5)Print "The string read is:%s"%(line)#Close FileFo.close ()
The result of the above example output is:
File name is: Runoob.txt
Read the first line 1:www.runoob.com
The string read is: 2:www
#-*-coding:utf-8-*-"""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 Print(Type (all_the_text))Print("all_the_text=", All_the_text)finally: 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=", line)Else: 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')#open a file in read moderesult =list ()Try: Lines=File_object2.readlines ()Print("type (lines) =", type (lines))#type (lines) = <type ' list ' > forLineinchLines#read each line sequentiallyline = Line.strip ()#remove the trailing blanks from each outfit if notLen (line)orLine.startswith ('#'):#determine if it is a blank line or comment line Continue #Yes, skip it, don't handle it .Result.append (line)#SaveResult.sort ()#Sort Results Print(Result)finally: File_object2.close () Open ('test_result.py','W'). Write ('%s'%'\ n'. Join (Result))#save into result file
Three ways Python reads a file read (), ReadLine (), ReadLines ()