python3 read readline和readlines详解

我们学习python基础的时候都知道,python 文件读取有三个常用方法:

  • read
  • readline
  • readlines
方法无参数有参数
read读取整个文件直到文件末尾读取固定大小字节(byte)数
readline读取整个文件的一行一直读取直到遇到\n 返回所读的整行数据读取文件固定大小的字节数返回字符串
readlines读取整个文件,返回值放到一个列表中这个比较复杂接下来回解释这个
# 文件 myfile.txt
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

使用 readline

f = open("myfile.txt", "rb")
line = f.readline()
print ("Read Line: %s" % (line))
line = f.readline(5)  # 带参数
print ("Read 5 of Line: %s" % (line))

##### ---运行结果--- #####
Read Line: This is 1st line

Read 5 of Line: This

使用 readlines

官方解释:

readlines(hint=-1, /) method of _io.BufferedReader instance Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

我们带示例文件

## myfile2.txt
ab
cdef
ghijklm
nop
qrmst

翻译过来理解为
hint 为参考字节大小
假设我们设置hint 为 5
如果当前行字节数(byte) 小于hint 值 则会继续读取下一行,如果读取完下一行还是小于hint值 则会继续读取,一直到读取字节数 >= hint值
如果当前行字节数大于 hint 值 则直接返回当前行

我们可以把 hint 值比作尺子,把文件到每一行比作长短不一的木头,我们要得到的是比尺子长的木头,长度不够到就几段拼起来

结合示例验证理解一下:

>>> f = open('myfile', 'rb')
>>> f.readlines(5)
[b'ab\n', b'cdef\n']
>>> f.readlines(5)
[b'ghijklm\n']
>>> f.readlines(5)
[b'nop\n', b'qrmst\n']
>>>

当读取大文件的时候可以选择 带参数的任意一种 安全起见还是选择前边的两种read 和 readline,如果你对你文件不信任,最好不要用readlines 带参数的方式,当文件中有一行数据的数据量非常大的时候对我们是非常不利的,因为它是超出读取却没有限制读取一行的大小,小心为好。

补充:
可以直接读取文件内容:

>>> fp  = open('myfile.txt', 'rb')
>>> type(fp)
<class '_io.BufferedReader'>
>>> for i in fp:
...     print(i)
...
b'This is 1st line\n'
b'This is 2nd line\n'
b'This is 3rd line\n'
b'This is 4th line\n'
b'This is 5th line\n'
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值