Three ways Python reads a file read (), ReadLine (), ReadLines ()

Source: Internet
Author: User

"""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 ()

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.