准备需要读取的文件:
#new.txt
hi
panpan
test
一、.read()
.read() 每次读取整个文件
file = "new.txt"
with open(file=file,mode="r",encoding="utf-8") as f:
r = f.read()
print("read输出:", r)
输出结果:
read输出: hi
panpan
test
二、.readline()
.readline() 只读取文件的一行
代码如下(示例):
file = "new.txt"
with open(file=file,mode="r",encoding="utf-8") as f:
rl = f.readline()
print("readline输出:",rl)
输出结果:
readline输出: hi
三、.readlines()
.readlines() 每次按行读取整个文件内容,将读取到的内容放到一个列表中,返回list类型,并且每一行后面都带有一个回车符‘\n’
file = "new.txt"
with open(file=file,mode="r",encoding="utf-8") as f:
rls = f.readlines()
print("readlines输出:",rls)
输出结果:
readlines输出: ['hi\n', 'panpan\n', 'test\n']