Python File read() 方法



Python File read() 方法读取文件的内容。默认情况下,此方法读取整个文件;如果接受可选参数,则仅指定 bytes。即使文件包含的字符数超过上述大小,文件中的其余字符也会被忽略。如果 read() 方法在获取所有字节之前命中 EOF,则它只读取文件中的可用字节。

仅当且仅当以任何读取模式打开文件时,才会执行此方法。这些读取模式要么是唯一的读取模式 (r),要么是读取和写入模式 (r+),要么是 Append 和 Read 模式 (a+)。

语法

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


 fileObject.read(size);

参数

  • size − (可选参数) 这是要从文件中读取的字节数。

返回值

此方法返回 string 中读取的字节。

考虑一个包含 5 行的现有文件,如下所示 -

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

以下示例显示了 Python File read() 方法的用法。在这里,我们在读取模式 (r) 下打开一个文件 “foo.txt”。然后,使用此方法读取 file 的所有内容(直到 EOF)。


# 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.read()
print("Read Line: %s" % (line))

# Close opened file
fo.close()

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

Name of the file: foo.txt
Read Line: This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

如果我们将一定数量的字节作为可选参数传递给该方法,则仅从文件中读取指定的字节。


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

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

# Close opened file
fo.close()

让我们编译并运行给定的程序,以产生如下输出 -

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

读取和写入操作可以在文件中一个接一个地完成。调用 read() 方法以检查使用 write() 方法添加到文件中的内容是否反映在当前文件中。

在下面的示例中,我们尝试使用 write() 方法将内容写入文件,然后关闭该文件。然后,此文件在 read (r) 模式下再次打开,并使用 read() 方法读取文件内容。


# Open a file in write mode
fo = open("foo.txt", "w")
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

# Write a new line
fo.write("This is the new line")

# Close opened file
fo.close()

# Open the file again in read mode
fo = open("foo.txt", "r")

line = fo.read()
print("File Contents:", line)

# Close opened file again
fo.close()

执行上述程序时,输出显示在终端上,如下所示 -

Name of the file: foo.txt
File Contents: This is the new line