Python File readline() 方法



Python File readline() 方法从文件中读取一整行。此方法在 read 行的末尾附加一个尾随换行符 ('\n')。

readline() 方法还接受一个可选参数,可以在其中指定要从包含换行符的行中读取的字节数。默认情况下,此可选参数将为 0,因此读取整行。

仅当立即遇到 EOF 时,才会返回空字符串。

注意:如果文件以普通读取模式打开,该方法以字符串形式返回该行。 如果文件以二进制读取模式打开,该方法将返回二进制对象。

语法

以下是 Python 文件 readline() 方法的语法 -


 fileObject.readline(size);

参数

  • size − 这是要从文件中读取的字节数。

返回值

此方法返回从文件中读取的行。

让我们使用现有文件 “foo.txt” 通过 Python File readline() 方法从中读取一行。foo.txt 文件中的内容如下 -

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

以下示例显示了上述演示文件中 readline() 方法的用法。


# 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.readline()
print("Read Line:", line)

# Close opened file
fo.close()

当我们运行上述程序时,它会产生以下结果——

Name of the file: foo.txt
Read Line: This is 1st line

但是如果我们传递一些值作为可选参数 size,该方法最多只读取给定的字节并在末尾附加换行符。


# 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.readline(5)
print("Read Line:", line)

# Close opened file
fo.close()

如果我们编译并运行上面的程序,结果会产生如下 -

Name of the file: foo.txt
Read Line: This

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

我们使用 open() 函数在读取二进制模式 (rb) 中打开一个现有文件 “foo.txt”。在 open() 方法返回的文件对象上调用 readline() 方法,以二进制形式获取作为文件一行的返回值。


# Open a file
fo = open("foo.txt", "rb")
print("Name of the file: ", fo.name)

line = fo.readline()
print("Read Line:", line)

# Passing the optional parameter
line = fo.readline(5)
print("Read Line:", line)

# Close opened file
fo.close()

编译并运行程序后,输出显示如下 -

Name of the file: foo.txt
Read Line: b'This is 1st line\r\n'
Read Line: b'This '

即使 size 参数大于当前文件中的行长度,该方法也仅返回整行。


# Open a file
fo = open("foo.txt", "r")
print("Name of the file: ", fo.name)

line = fo.readline(40)
print("Read Line:", line)

# Close opened file
fo.close()

让我们编译并运行给定的程序,输出显示如下 -

Name of the file: foo.txt
Read Line: This is 1st line