Python File readlines() 方法一次性读取文件中的所有行。这意味着,将持续读取文件,直到命中 End Of File(或 EOF)。可以通过在内部使用 readline() 方法来实现。
此方法仅适用于较小的文件,因为文件内容被读入内存,然后将行分成单独的行。readlines() 方法还接受一个可选参数,我们可以在其中限制要读取的字节数。
仅当立即遇到 EOF 时,才会返回空字符串。
语法
以下是 Python 文件 readlines() 方法的语法 -
fileObject.readlines(sizehint);
参数
- sizehint − 这是要从文件中读取的字节数。
返回值
此方法返回包含行的列表。
例让我们使用现有文件 “foo.txt” 通过 readlines() 方法从中读取行。foo.txt 文件中的内容如下 -
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
以下示例显示了 Python File readlines() 方法的用法。
# Open a file
fo = open("foo.txt", "r+")
print("Name of the file: ", fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readlines()
print("Read Line: ", line)
# Close opened file
fo.close()
当我们运行上述程序时,它会产生以下结果——
Name of the file: foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line']
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line']
例
但是,如果我们将一些值作为可选参数 sizehint 传递,则此方法仅读取给定的字节并在末尾附加换行符。但是,如果参数小于第一行的长度,该方法仍返回完整的第一行。
# Open a file
fo = open("foo.txt", "r+")
print("Name of the file: ", fo.name)
# Passing the size argument to the readline() method
line = fo.readlines(2)
print("Read Line:", line)
# Close opened file
fo.close()
如果我们编译并运行上面的程序,结果会产生如下 -
Name of the file: foo.txt
Read Line: ['This is 1st line\n']
Read Line: ['This is 1st line\n']
例
现在,如果文件以读取二进制模式 (rb) 打开,则此方法返回二进制对象。
我们使用 open() 函数在读取二进制模式 (rb) 中打开一个现有文件 “foo.txt”。在表示此文件的文件对象上调用 readlines() 方法,以获取二进制形式的返回值作为其内容。在这种情况下,如果参数小于第一行的长度,该方法将返回一个空列表。
# Open a file
fo = open("foo.txt", "rb")
print("Name of the file: ", fo.name)
line = fo.readlines()
print("Read Line:", line)
# Passing the optional parameter
line = fo.readlines(3)
print("Read Line:", line)
# Close opened file
fo.close()
编译并运行程序后,输出显示如下 -
Name of the file: foo.txt
Read Line: [b'This is 1st line\r\n', b'This is 2nd line\r\n', b'This is 3rd line\r\n', b'This is 4th line\r\n', b'This is 5th line']
Read Line: []
Read Line: [b'This is 1st line\r\n', b'This is 2nd line\r\n', b'This is 3rd line\r\n', b'This is 4th line\r\n', b'This is 5th line']
Read Line: []
例
即使 size 参数大于当前文件中内容的长度,此方法仍返回文件中的所有行。
# Open a file
fo = open("foo.txt", "r")
print("Name of the file: ", fo.name)
line = fo.readlines(120)
print("Read Line:", line)
# Close opened file
fo.close()
让我们编译并运行给定的程序,输出显示如下 -
Name of the file: foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line']
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line']