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模块,输出文件的指定行。
相关文章推荐
- Python中read()、readline()和readlines()三者间的区别和用法
- Python中read()、readline()和readlines()三者间的区别和用法
- Python中read()、readline()和readlines()三者间的区别和用法
- Python--read()和readline()以及readlines()用法区别
- python中.read(),.readline(),.readlines()的区别
- python中read() readline()以及readlines()用法
- python中读取文件函数read()、readline()、readlines()的区别
- python:read,readlines,readline的区别
- python中read() readline()以及readlines()用法
- python中read() readline()以及readlines()用法
- python中read() readline()以及readlines()区别
- Python中三个读文件函数read、readline和readlines的简要区别
- python中read、readline、readlines的区别
- python read() readline() readlines() write() writelines()方法总结与区别
- read,readline与readlines的用法及区别
- python中read() readline()以及readlines()用法
- python中read() readline()以及readlines()区别 .
- python读文件read()、readline()、readlines()三个方法的区别
- python中read、readline和readlines的区别
- python-read()、readline()以及readlines()之间的区别