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

Python3 File readline() Method

Python3 File readline() Method

Python3 File Methods Python3 File methods


Overview

readline() The method reads a whole line from a file, including the "\n" character. If a non-negative argument is given, it returns the specified number of bytes, including the "\n" character.

Syntax

The readline() method syntax is as follows:


fileObject.readline(); 

Parameters

Return Value

Returns the bytes read from the string.

Example

The following example shows how to use the readline() 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:

Example

#!/usr/bin/python3

Opening a File

fo

=

open

(

"runoob.txt"

,

"r+"

)

print

(

"File name: "

,

fo.

name

)

line

=

fo.

readline

(

)

print

(

"Read the first line %s"

%

(

line

)

)

line

=

fo.

readline

(

5

)

print

(

"The string read is: %s"

%

(

line

)

)

Closing a File

fo.

close

(

)

The output of the above example is:


文件名为:  runoob.txt
读取第一行 1:www.runoob.com

读取的字符串为: 2:www

Python3 File Methods Python3 File methods