Python 文件 read() 方法



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

此方法仅当文件以任何读取模式打开时才执行。这些读取模式或者是只读模式 (r)、读写模式 (r+) 和追加读取模式 (a+)。

语法

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

fileObject.read(size);

参数

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

返回值

此方法返回以字符串形式读取的字节。

示例

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

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

以下示例演示了 Python 文件 read() 方法的用法。在这里,我们以读取模式 (r) 打开文件“foo.txt”。然后使用此方法读取文件的全部内容(直到 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() 方法将内容写入文件,然后关闭文件。然后,此文件再次以读取 (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
python_file_methods.htm
广告