您的位置:首页 > 编程语言 > Python开发

python+read()+、readline()和+readlines()的区别和用法

2017-10-17 10:15 971 查看
with open('ceshi.txt','r',encoding='utf-8') as f:
data = f.read()
print(data)
print(type(data))


Hello world
python
Welcome
How are you

<class 'str'>


with open('ceshi.txt','r',encoding='utf-8') as f:
lines = f.readlines()
print(lines)
print(type(lines))


['Hello world\n', 'python\n', 'Welcome\n', 'How are you\n', '\n']
<class 'list'>


with open('ceshi.txt','r',encoding='utf-8') as f:
line = f.readline()
while line:
print(line)
print(type(line))
line= f.readline()


Hello world

<class 'str'>
python

<class 'str'>
Welcome

<class 'str'>
How are you

<class 'str'>

<class 'str'>


read([size])方法从文件当前位置起读取size个字节,若无参数size,则表示读取至文件结束为止,它范围为字符串对象。

readline()方法每次读出一行内容,所以,读取时占用内存小,比较适合大文件,该方法返回的是一个字符串对象。

readlines()方法读出整个文件所有行内容,保存在一个列表(list)中,每行作为一个元素,但读取大文件会比较占内存。

import linecache
text = linecache.getline('ceshi.txt',2)
print(text)


python


也可以引入linecache模块,输出文件的指定行。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: