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

Python File readline() method

Python File readline() method

Python File methods Python 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(size)

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 in a loop:



#!/usr/bin/python

# -*- coding: UTF-8 -*-



# Open file

fo = open("runoob.txt", "rw+")

print "文件名为: ", fo.name



line = fo.readline()

print "读取第一行 %s" % (line)



line = fo.readline(5)

print "读取的字符串为: %s" % (line)



# Close file

fo.close()

The output of the above example is:



文件名为:  runoob.txt

读取第一行 1:www.runoob.com



读取的字符串为: 2:www

Python File methods Python File methods