当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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