简单介绍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 杀死自身进程的实现方法

有时候我们需要中断程序的执行,比如执行如下代码失败时。 import tensorflow as tf tf.enable_eager_execution() 这时我们可以杀...

跟老齐学Python之使用Python查询更新数据库

回顾一下已有的战果:(1)连接数据库;(2)建立指针;(3)通过指针插入记录;(4)提交将插入结果保存到数据库。在交互模式中,先温故,再知新。 复制代码 代码如下: >>&g...

python批量替换多文件字符串问题详解

系统如下: 操作系统 : CentOS7.3.1611_x64 Python 版本 : 2.7.5 问题描述 编码过程中有时候会遇到在多个源文件中存在同一个变量名(比如 : write...

Python多进程同步简单实现代码

本文讲述了Python多进程同步简单实现代码。分享给大家供大家参考,具体如下: #encoding=utf8 from multiprocessing import Process,...

gearman的安装启动及python API使用实例

本文讲述了gearman的安装启动及python API使用实例,对于网站建设及服务器维护来说非常有用! 一、概述: Gearman是一款非常优秀的任务分发框架,可以用于分布式计算。具体...