當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python File readlines()用法及代碼示例


文件 readlines() 方法

readlines() 方法是 Python 中的一個內置方法,用於獲取文件中的所有行,使用該對象(當前文件流/IO 對象)調用該方法並返回文件中所有可用的行,我們也可以指定總行數從行中讀取的字節數。

用法:

    file_object.readlines(len)

參數:

  • len– 它是一個可選參數,可用於指定要從文件中讀取的總字節數。它的默認值是 -1,指定所有行。如果len大於文件的總字節數,則不會返回更多內容。

返回值:

這個方法的返回類型是<class 'list'>,它以列表的形式返回行。

例:

# Python File readlines() Method with Example

# creating a file
myfile1 = open("hello1.txt", "w")

# writing content in the file
myfile1.write("Shivang, 21, Indore\n")
myfile1.write("Pankaj, 27, Mumbai\n")
myfile1.write("Rambha, 16, Indraloka\n")
myfile1.write("Urvarshi, 18, Indraloka\n")
myfile1.write("Menaka, 17, Indraloka\n")

# closing the file
myfile1.close()

# reading the file (opening file in 'r' mode)
myfile1 = open("hello1.txt","r")

# reading and printing the file's content  
# using readlines()
print("file's content (using readlines() method)...")
print("myfile1.readlines()...")
print(myfile1.readlines())

# reading a total number of bytes
# seeking file's position to 0th position
myfile1.seek(0)
# reads only 10 bytes
print("myfile1.readlines(10)...")
print(myfile1.readlines(10))

# reads next 300 bytes, if no more bytes
# method will not read more bytes
print("myfile1.readlines(300)...")
print(myfile1.readlines(300))

# closing the file
myfile1.close()

輸出

file's content (using readlines() method)...
myfile1.readlines()...
['Shivang, 21, Indore\n', 'Pankaj, 27, Mumbai\n', 'Rambha, 16,Indraloka\n', 'Urvarshi, 18, Indraloka\n', 'Menaka, 17, Indraloka\n']
myfile1.readlines(10)...
['Shivang, 21, Indore\n']
myfile1.readlines(300)...
['Pankaj, 27, Mumbai\n', 'Rambha, 16, Indraloka\n', 'Urvarshi,18, Indraloka\n', 'Menaka, 17, Indraloka\n']


相關用法


注:本文由純淨天空篩選整理自 Python File readlines() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。