Python3 File read() Method

Python3 File Methods


Overview

read()The method is used to read the specified number of characters from the file (text modet) or bytes (binary modeb). If the parameter is not givensizeorsizeor is negative, read all contents of the file.

Syntax

The syntax of the read() method is as follows:

fileObject.read([size]); 

Parameters

  • sizesize -- The number of characters (text mode) or bytes (binary mode) to read from the file. It defaults to-1, indicating that the entire file is read.

Return Value

Returns the bytes read from the string.

Example

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

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

This is line one
This is line two
This is line three
This is line four
This is line five

Read the file contents in a loop:

Example

#!/usr/bin/python3

# Open the file
fo = open("example.txt", "r+")
print ("File name: ", fo.name)

line = fo.read(10)
print ("String read: %s" % (line))

# Close the file
fo.close()

The output of the above example is:

文件名为:  example.txt
读取的字符串: 这是第一行
这是第二

Python3 File Methods

Other Extensions