Python bit record 8: file operation read, ReadLine and ReadLines

Source: Internet
Author: User

There are three ways Python reads the contents of a file: Read (), ReadLine (), and ReadLines ()

There are three different ways to do this:

Read (...)        Read ([size]), read at most size bytes, returned as a string.    If the size argument is negative or omitted, read until EOF is reached.  Notice that while in non-blocking mode, less data than what is requested may is returned, even if no size parameter was Given.

Simply put, the read () method does not specify the number of bytes to read, and the default reads the entire file content (memory exists for all file contents), generating a string.

ReadLine (...)          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 is returned then). Return an empty string at EOF.

Simply put, the ReadLine () method does not specify the number of bytes to read, and the default reads one line at a time, generating a string. Each time the ReadLine () method is executed, a row of the file is read. A loop is available to complete the read of the entire file.


ReadLines (...)        ReadLines ([size]), List of strings, each a line from the file.    Call ReadLine () repeatedly and return a list of the lines so read. The optional size argument, if given, is a approximate bound on the all number of bytes in the lines returned.

Simply put, the ReadLines () method does not specify the number of bytes to read, by default reads the entire file contents (memory exists for all file contents) and generates a list. Each element in the list is a row of files. There is no line to print for the For loop.


Note: For very large files, it is not appropriate to use the read () and ReadLines () methods. Because both of these methods are used to read the contents of the file into memory at once.

Python bit record 8: file operation read, ReadLine and ReadLines

Related Article

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.