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

Python File read() Method

Python File read() Method

Python File methods Python File methods


Overview

read() The method reads a specified number of bytes from a file; if not given or negative, it reads all.

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:


1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com

Read the file's contents in a loop:

Example

#!/usr/bin/python

-- coding: UTF-8 --

Opening a File

fo

=

open

(

"runoob.txt"

,

"rw+"

)

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
读取的字符串: 1:www.runo

Python File methods Python File methods