Python 3 教程教程
Python3 File readline() 方法
Python3 File readline() 方法
Python3 File readline() 方法
概述
readline() 方法用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。
语法
readline() 方法语法如下:
fileObject.readline();
参数
-
size -- 从文件中读取的字节数。
返回值
返回从字符串中读取的字节。
实例
以下实例演示了 readline() 方法的使用:
文件 verydoc.txt 的内容如下:
1:www.verydoc.net 2:www.verydoc.net 3:www.verydoc.net 4:www.verydoc.net 5:www.verydoc.net
读取文件的内容:
实例
#!/usr/bin/python3
# 打开文件
fo = open("verydoc.txt", "r+")
print ("文件名为: ", fo.name)
line = fo.readline()
print ("读取第一行 %s" % (line))
line = fo.readline(5)
print ("读取的字符串为: %s" % (line))
# 关闭文件
fo.close()
# 打开文件
fo = open("verydoc.txt", "r+")
print ("文件名为: ", fo.name)
line = fo.readline()
print ("读取第一行 %s" % (line))
line = fo.readline(5)
print ("读取的字符串为: %s" % (line))
# 关闭文件
fo.close()
以上实例输出结果为:
文件名为: verydoc.txt 读取第一行 1:www.verydoc.net 读取的字符串为: 2:www
Python3 File readline() 方法 |
---|
Python 3 教程
Python的3.0版本,常被称为Python 3000,或简称Py3k。相对于Python的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0在设计的时候没有考虑向下兼容。