文件 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 readline()用法及代碼示例
- Python File read()用法及代碼示例
- Python File readable()用法及代碼示例
- Python File tell()用法及代碼示例
- Python File seek()用法及代碼示例
- Python File flush()用法及代碼示例
- Python File write()用法及代碼示例
- Python File truncate()用法及代碼示例
- Python File fileno()用法及代碼示例
- Python File open()用法及代碼示例
- Python File isatty()用法及代碼示例
- Python File writable()用法及代碼示例
- Python File writelines()用法及代碼示例
- Python File close()用法及代碼示例
- Python File seekable()用法及代碼示例
- Python numpy.less()用法及代碼示例
- Python Sympy Permutation.list()用法及代碼示例
- Python Matplotlib.figure.Figure.subplots_adjust()用法及代碼示例
- Python numpy.tril()用法及代碼示例
- Python Matplotlib.pyplot.matshow()用法及代碼示例
注:本文由純淨天空篩選整理自 Python File readlines() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。