計算機二級python語言中readlines()參數讀取行數問題詳細分析

在計算機二級python中介紹的 f.readlines(hint = -1)

含義爲:從文件中讀入所有行,以每行爲元素形成一個列表。參數可選,如果給出,讀入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']

點擊獲取計算機二級python全套教程:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章