我们学习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'