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模块,输出文件的指定行。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐