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://codercto.com/courses/l/8.html

查看所有标签

Code Reading

Code Reading

Diomidis Spinellis / Addison-Wesley Professional / 2003-06-06 / USD 64.99

This book is a unique and essential reference that focuses upon the reading and comprehension of existing software code. While code reading is an important task faced by the vast majority of students,......一起来看看 《Code Reading》 这本书的介绍吧!

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试