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

yipeiwu_com5年前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

相关文章

详解Django 中是否使用时区的区别

起步 在 Django 的模型中新加了一个日期的字段: import datetime class Instance(models.Model): ... start_ti...

python微信跳一跳系列之棋子定位颜色识别

python微信跳一跳系列之棋子定位颜色识别

python微信跳一跳,前言 这是python玩跳一跳系列博文中一篇,主要内容是用颜色识别的方法来进行跳跳小人的定位。 颜色识别 通过观察,我们可以发现,尽管背景和棋子在不停的变化,但...

python监控进程状态,记录重启时间及进程号的实例

本脚本为本人在性能测试过程中编写,用于对进程状态的监控,也可以用于日常的监控,适用性一般,扩展性还行 # -*- coding: UTF-8 -*- # author=baird_x...

numpy返回array中元素的index方法

如下所示: import numpy a = numpy.array(([3,2,1],[2,5,7],[4,7,8])) itemindex = numpy.argwhere(a...

python+selenium实现京东自动登录及秒杀功能

本文实例为大家分享了selenium+python京东自动登录及秒杀的代码,供大家参考,具体内容如下 运行环境: python 2.7 python安装selenium 安装webdr...