8. Loop body and file

Source: Internet
Author: User

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:
  1. readline([size])-> next line from the file, as a string.
  2. Retain newline. A non-negative size argument limits the maximum
  3. number of bytes to return(an incomplete line may be returned then).
  4. Return an empty string at EO
Read the following:
    1. < Code class= "Language-c" > content:
    2. ID , name Span class= "pun", score
    3. 1302303069 qxj511 98.80
    4. 1302303070 , Zhy 99.90
  1. 依次读取:
  2. fd = open("qxj511.txt","r+")
  3. print fd.readline()
  4. print fd.readline()
  5. fd.close()
  6. 打印:
  7. ID, name, score
  8. 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:
  1. fd = open("qxj511.txt","r")
  2. s = fd.readline() // 读取第一行
  3. while s !="": // 判断读取的结果是否为空
  4. s = s.rstrip("\n") // 删除字符串后面的 \n
  5. print s // 打印字符串
  6. s = fd.readline() // 重新读取一行
  7. fd.close() // 当读取完毕的时候,也就是 readline 返回值为零
2. forThis completes the read and write of the while completion file, and now uses the for
  1. fd = open("qxj511.txt","r")
  2. for st in fd:
  3. print st
  4. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.