Python 文件 readlines() 方法



Python 文件 readlines() 方法一次性读取文件中的所有行。这意味着,文件会连续读取,直到遇到文件结尾 (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

以下示例演示了 Python 文件 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']

示例

但是,如果我们将某些值作为可选参数 *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']

示例

现在,如果文件以二进制读取模式 (rb) 打开,此方法将返回二进制对象。

我们使用 open() 函数以二进制读取模式 (rb) 打开现有的文件“foo.txt”。在表示此文件的 file 对象上调用 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: []

示例

即使 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']
python_file_methods.htm
广告