在计算机二级python中介绍的 f.readlines(hint = -1)
含义为:从文件中读入所有行,以每行为元素形成一个列表。参数可选,如果给出,读入hint行。说法是不准确的
关于hint的参数存在一些问题,例如代码:hint的参数存在一些问题,例如代码:
f = open("a.txt","r")
a = f.readlines(2)
print(a)
f.close()
其中a.txt文本的内容为如下:
12345
67890
abcdefghjkomn
打印输出的结果为:
>>>[12345\n]
并不是打印输出了a.txt文本中的两行内容。
这里的存在的 问题就在于 参数hint并不是直接指示所对应的行数。
Python官方文档给出的内容解释为:
readlines(hint=-1, /) method of _io.TextIOWrapper 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.
翻译:hint参数可以指定提示来控制读取的行数:如果到目前为止所有行的总大小(以字节/字符为单位)超过提示,则不会再读取任何行。
通俗来说:hint参数是字节的总大小,会读取到该文件内对应字节数的当前行。
第一行如果有5个字符,hint=5,就只读取第一行,(hint<=5时都只会读取第一行的内容)
第二行如果有5个字符,hint=6,会开始读取第二行内容。(5<=hint<=11时时会读取到前两行的内容)
例如 1 :hint的参数为5时
f = open("a.txt","r")
a = f.readlines(5)
print(a)
f.close()
输出为>>>[12345\n]
例如 2 :hint参数为6时
f = open("a.txt","r")
a = f.readlines(6)
print(a)
f.close()
输出为>>>[12345\n, 67890\n]
例如 3 :hint参数为11时:
f = open("a.txt","r")
a = f.readlines(11)
print(a)
f.close()
输出为>>>[12345\n, 67890\n]
注意:每一行有一个\n代表回车符,当遇到\n时会开始读取下一行,但\n本身占一个字符。
例如4:hint参数为12时:
f = open("a.txt","r")
a = f.readlines(12)
print(a)
f.close()
输出为>>>[12345\n, 67890\n, abcdefghjkomn]