关于python中readlines函数的参数hint的相关知识总结

readlines的帮助信息

>>> fr=open('readme.txt')>>> help(fr.readlines)Help on built-in function readlines: readlines(hint=-1, /) method of _io.TextIOWrapper instanceReturn a list of lines from the stream.hint can be specified to control the number of lines read: no morelines will be read if the total size (in bytes/characters) of alllines so far exceeds hint.

Google翻译
_io.TextIOWrapper 实例的 readlines(hint=-1, /) 方法
从流中返回行列表。

可以指定 hint 来控制读取的行数:如果到目前为止所有行的总大小(以字节/字符为单位)超过hint,则不会读取更多行。
readme.txt中的内容 关于python中readlines函数的参数hint的相关知识总结
文章图片

>>> f=open('readme.txt')>>> f.readlines()['1\n', '22\n', '\n', '333']

为了进一步搞清楚hint,我写了一个函数来演示
readlines函数代码
def readlinesFile(filename,nbyte):'''探索f.readlines(i)中i的作用,典型的调用形式:readlinesFile('readme.txt',12)'''for i in range(nbyte):f=open(filename)ss=f.readlines(i)if i==0:#如果hint=0,先把每一个元素输出textline=len(ss)#文件的总行数ntotalbyte=0#文件的总字数nwritebyte=0#已经写了的字节数for j in range(textline):#nwritebyte=ntotalbyte#已经写了的字节数ntotalbyte=ntotalbyte+len(ss[j])rowbyte=0#已经写了的新行的字节数,用来记一行已经输出的字节个数while nwritebyte
【关于python中readlines函数的参数hint的相关知识总结】输出
>>> readlinesFile('readme.txt',12)
1: '1'
2: '\n'
3: '2'
4: '2'
5: '\n'
6: '\n'
7: '3'
8: '3'
9: '3'
行数=4,字数=9
f.readlines0=['1\n', '22\n', '\n', '333']
f.readlines1=['1\n']
f.readlines2=['1\n', '22\n']
f.readlines3=['1\n', '22\n']
f.readlines4=['1\n', '22\n']
f.readlines5=['1\n', '22\n', '\n']
f.readlines6=['1\n', '22\n', '\n', '333']
f.readlines7=['1\n', '22\n', '\n', '333']
f.readlines8=['1\n', '22\n', '\n', '333']
f.readlines9=['1\n', '22\n', '\n', '333']
f.readlines10=['1\n', '22\n', '\n', '333']
f.readlines11=['1\n', '22\n', '\n', '333']
总结: 1.hint 是要输出显示的字节数
2.hint 默认等于-1,就是以列表的形式读出所有内容
3.hint = 0时,效果等同于-1
4.hint 所指的字节数正好是换行符的话,则实际输出是 hint+1
更花哨的readlinesFile
def readlinesFile(filename,nbyte):'''探索f.readlines(i)中i是指什么,典型的调用形式:readlinesFile('readme.txt',12)'''specialByte=[]#存储特殊的字节数用for i in range(nbyte):with open(filename) as f:#使用with语句就可以不使用f.close()了ss=f.readlines(i)if(i==0):#如果hint=0,先把每一个元素输出print(ss)textline=len(ss)#文件的总行数ntotalbyte=0#文件的总字数nwritebyte=0#已经写了的字节数for j in range(textline):#nwritebyte=ntotalbyte#已经写了的字节数ntotalbyte=ntotalbyte+len(ss[j])rowbyte=0#已经写了的新行的字节数,用来记一行已经输出的字节个数while nwritebyte
效果
关于python中readlines函数的参数hint的相关知识总结
文章图片

参考文章:https://www.jb51.net/article/206578.htm
到此这篇关于关于python中readlines函数的参数hint的相关知识总结的文章就介绍到这了,更多相关python readlines函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读