Python file Read () method

Source: Internet
Author: User
Overview

The read () method of the Python file is used to read the specified number of characters from a file and read all if not given or negative.

Grammar

The read () method syntax is as follows:

Fileobject.read ([size])
Parameters
  • size -the number of characters to read from the file, including the "\ n" character.

return value

Returns the characters that are read from the string.

Instance

The following example demonstrates the use of the Read () method:

The contents of the file Runoob.txt are as follows:

This is the first line, this is the second line, this is line three, this is line fourth, this is line fifth.

To iterate through the contents of a file:

#!/usr/bin/python3# Open the file fo = open ("Runoob.txt", "r+", encoding= "Utf-8") print ("File name:", fo.name) line = Fo.read () print ( "Read string:%s"% (line)) # Close file Fo.close ()

The result of the above example output is:

The file name is:  runoob.txt Read the string: This is the first line this is the second

Python file Read () method

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.