Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 File read() Method

Python3 File read() Method

Python3 File Methods Python3 File methods


Overview

read() The method reads the specified number of characters (text mode t) or bytes (binary mode b) from a file; if the argument is not given or size or size is negative, it reads the entire file.

Syntax

The read() method syntax is as follows:


fileObject.read([size]); 

Parameters

Return Value

Returns the bytes read from the string.

Example

The following example shows how to use the read() method:

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


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

Read the file's contents in a loop:

Example

#!/usr/bin/python3

Opening a File

fo

=

open

(

"runoob.txt"

,

"r+"

)

print

(

"File name: "

,

fo.

name

)

line

=

fo.

read

(

10

)

print

(

"String read: %s"

%

(

line

)

)

Closing a File

fo.

close

(

)

The output of the above example is:


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

Python3 File Methods Python3 File methods