简单介绍Python中的readline()方法的使用

yipeiwu_com6年前Python基础

 readline()方法从文件中读取一整行。尾部的换行符保持在字符串中。如果大小参数且非负,那么一个最大字节数,包括结尾的换行和不完整的行可能会返回。

遇到EOF时立即返回一个空字符串。
语法

以下是readline()方法的语法:

fileObject.readline( size );

参数

  •     size -- 这是可以从文件中读取的字节数。

返回值

此方法返回从文件中读取的行。
例子

下面的例子显示了readline()方法的使用。

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readline()
print "Read Line: %s" % (line)

line = fo.readline(5)
print "Read Line: %s" % (line)

# Close opend file
fo.close()

当我们运行上面的程序,它会产生以下结果:

Name of the file: foo.txt
Read Line: This is 1st line

Read Line: This

相关文章

python实现矩阵乘法的方法

本文实例讲述了python实现矩阵乘法的方法。分享给大家供大家参考。具体实现方法如下: def matrixMul(A, B): res = [[0] * len(B[0]) f...

python 在屏幕上逐字显示一行字的实例

如下所示: #-*- coding: utf-8 -*- #code:myhaspl@qq.com #12-1.py import sys reload(sys) sys.setde...

python实现生成Word、docx文件的方法分析

本文实例讲述了python实现生成Word、docx文件的方法。分享给大家供大家参考,具体如下: http://python-docx.readthedocs.io/en/latest/...

python中获得当前目录和上级目录的实现方法

获取当前文件的路径: from os import path d = path.dirname(__file__) #返回当前文件所在的目录 # __file__ 为当前文件...

Python文件处理

本文给大家介绍Python文件处理相关知识,具体内容如下所示: 1.文件的常见操作 文件是日常编程中常用的操作,通常用于存储数据或应用系统的参数。python提供了os、os.path...