Easy Tutorial
❮ Python Os Ftruncate Python String Istitle ❯

Python3 File read() Method

Python3 File Methods


Overview

The read() method is used to read a specified number of characters (in text mode t) or bytes (in binary mode b) from a file. If the size parameter is not provided or is negative, the entire contents of the file are read.

Syntax

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

fileObject.read([size]);

Parameters

Return Value

Returns the bytes read from the string.

Example

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

The content of the file "tutorialpro.txt" is as follows:

这是第一行
这是第二行
这是第三行
这是第四行
这是第五行

Loop to read the contents of the file:

Example

#!/usr/bin/python3

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

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

# Close file
fo.close()

The output of the above example is:

File name:  tutorialpro.txt
Read string: 这是第一行
这是第二

Python3 File Methods

❮ Python Os Ftruncate Python String Istitle ❯