文件 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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。