[英]Python's function readlines(n) behavior
我已經閱讀了文檔,但是readlines(n)
是做什么的? 通過readlines(n)
,我的意思是readlines(3)
或任何其他數字。
當我運行readlines(3)
時,它返回與readlines()
相同的內容。
可選參數應該表示從文件中讀取了多少(大約)字節。 該文件將被進一步讀取,直到當前行結束:
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
另一個引用:
如果給定一個可選參數sizehint ,它會從文件中讀取那么多字節以及足夠多的字節來完成一行,並從中返回這些行。
沒錯,它似乎對小文件沒有多大作用,這很有趣:
In [1]: open('hello').readlines()
Out[1]: ['Hello\n', 'there\n', '!\n']
In [2]: open('hello').readlines(2)
Out[2]: ['Hello\n', 'there\n', '!\n']
有人可能會認為它是由文檔中的以下短語解釋的:
使用 readline() 讀取直到 EOF 並返回包含如此讀取的行的列表。 如果存在可選的 sizehint 參數,而不是讀取到 EOF,而是讀取總計大約 sizehint 字節的整行(可能在四舍五入到內部緩沖區大小之后) 。 如果 sizehint 無法實現或無法有效實現,則實現類文件接口的對象可能會選擇忽略它。
但是,即使我嘗試在沒有緩沖的情況下讀取文件,它似乎也沒有改變任何東西,這意味着其他類型的內部緩沖區是指:
In [4]: open('hello', 'r', 0).readlines(2)
Out[4]: ['Hello\n', 'there\n', '!\n']
在我的系統上,這個內部緩沖區大小似乎約為 5k 字節/1.7k 行:
In [1]: len(open('hello', 'r', 0).readlines(5))
Out[1]: 1756
In [2]: len(open('hello', 'r', 0).readlines())
Out[2]: 28080
根據文件的大小, readlines(hint) 應該返回一組較小的行。 從文檔中:
f.readlines() returns a list containing all the lines of data in the file.
If given an optional parameter sizehint, it reads that many bytes from the file
and enough more to complete a line, and returns the lines from that.
This is often used to allow efficient reading of a large file by lines,
but without having to load the entire file in memory. Only complete lines
will be returned.
因此,如果您的文件有 1000 行,您可以傳入說... 65536,它一次只能讀取那么多字節 + 足以完成下一行,返回所有已完全讀取的行。
它列出了行,給定字符大小“n”從當前行開始跨越這些行。
例如:在一個text
文件中,內容為
one
two
three
four
open('text').readlines(0)
返回['one\n', 'two\n', 'three\n', 'four\n']
open('text').readlines(1)
返回['one\n']
open('text').readlines(3)
返回['one\n']
open('text').readlines(4)
返回['one\n', 'two\n']
open('text').readlines(7)
返回['one\n', 'two\n']
open('text').readlines(8)
返回['one\n', 'two\n', 'three\n']
open('text').readlines(100)
返回['one\n', 'two\n', 'three\n', 'four\n']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.