Python File readline() 方法

Python 教程 · 2019-02-03 15:12:36

概述

readline() 方法用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。

语法

readline() 方法语法如下:

fileObject.readline(); 

参数

  • size -- 从文件中读取的字节数。

返回值

返回从字符串中读取的字节。

实例

以下实例演示了 readline() 方法的使用:

文件 codercto.txt 的内容如下:

1:www.codercto.com
2:www.codercto.com
3:www.codercto.com
4:www.codercto.com
5:www.codercto.com

循环读取文件的内容:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开文件
fo = open("codercto.txt", "rw+")
print "文件名为: ", fo.name

line = fo.readline()
print "读取第一行 %s" % (line)

line = fo.readline(5)
print "读取的字符串为: %s" % (line)

# 关闭文件
fo.close()

以上实例输出结果为:

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

读取的字符串为: 2:www

点击查看所有 Python 教程 文章: https://www.codercto.com/courses/l/8.html

查看所有标签

Distributed Systems

Distributed Systems

Sukumar Ghosh / Chapman and Hall/CRC / 2014-7-14 / USD 119.95

Distributed Systems: An Algorithmic Approach, Second Edition provides a balanced and straightforward treatment of the underlying theory and practical applications of distributed computing. As in the p......一起来看看 《Distributed Systems》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具