as the name implies, the operation of the file is performed through the loop body.
1. whilefor the file read, the use of read, is a one-time all read out, for the very large file, then you can use the ReadLine function, each read a row, the return value is the result of reading, when all finished reading, the return value is empty:
readline([size])-> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return(an incomplete line may be returned then).
Return an empty string at EO
Read the following:
- < Code class= "Language-c" > content:
ID , name Span class= "pun", score
1302303069 qxj511 98.80
1302303070 , Zhy 99.90
依次读取:
fd = open("qxj511.txt","r+")
print fd.readline()
print fd.readline()
fd.close()
打印:
ID, name, score
1302303069, qxj511,98.80
in a process readline, each time you finish reading a line, print. When ReadLine is used again, it is read from the next line that was last read.
read by line:
fd = open("qxj511.txt","r")
s = fd.readline() // 读取第一行
while s !="": // 判断读取的结果是否为空
s = s.rstrip("\n") // 删除字符串后面的 \n
print s // 打印字符串
s = fd.readline() // 重新读取一行
fd.close() // 当读取完毕的时候,也就是 readline 返回值为零
2. forThis completes the read and write of the while completion file, and now uses the for
fd = open("qxj511.txt","r")
for st in fd:
print st
fd.close()
using this method, you can also read and print the text line by line, which involves the knowledge of iterators. When a for is present, the iterator's next is used, each time the data of the open file is obtained, and when the iterator executes, the iterator returns an exception so that the For loop ends.
From for notes (Wiz)
8. Loop body and file