Python 简明教程

Python - Read Files

从文件中读取涉及打开文件、读取其内容,然后关闭文件释放系统资源。Python 提供了多种从文件中读取的方法,每种方法都适合不同的用例。

Reading from a file involves opening the file, reading its contents, and then closing the file to free up system resources. Python provides several methods to read from a file, each suited for different use cases.

Opening a File for Reading

打开文件是读取其内容的第一步。在 Python 中,可以使用 open() 函数打开文件。此函数至少需要一个 filename 的参数,还可以使用 mode 来指定文件打开的目的。

Opening a file is the first step in reading its contents. In Python, you use the open() function to open a file. This function requires at least one argument, the filename, and optionally a mode that specifies the purpose of opening the file.

若要打开一个文件来读取,可以使用模式 'r' 。这是默认模式,所以如果您只需要从文件中读取,可以省略此模式。

To open a file for reading, you use the mode 'r'. This is the default mode, so you can omit it if you only need to read from the file.

Reading a File Using read() Method

read() 方法用于在 Python 中读取文件内容。它将文件的整个内容读作一个字符串。当需要一次处理整个文件时,此方法特别有用。

The read() method is used to read the contents of a file in Python. It reads the entire content of the file as a single string. This method is particularly useful when you need to process the whole file at once.

Syntax

以下是 Python 中 read() 方法的基本语法−

Following is the basic syntax of the read() method in Python −

file_object.read(size)

其中,

Where,

  1. file_object is the file object returned by the open() function.

  2. size is the number of bytes to read from the file. This parameter is optional. If omitted or set to a negative value, the method reads until the end of the file.

Example

在以下示例中,以只读模式打开文件“example.txt”。然后使用 read() 方法读取文件的整个内容 −

In the following example, we are opening the file "example.txt" in read mode. We then use the read() method to read the entire content of the file −

# Open the file in read mode
file = open('example.txt', 'r')

# Read the entire content of the file
content = file.read()

# Print the content
print(content)

# Close the file
file.close()

执行上面的代码后,我们得到以下输出: -

After executing the above code, we get the following output −

welcome to Tutorialspoint.

Reading a File Using readline() Method

readline() 方法用于一次从文件中读取一行。当需要逐行处理文件时此方法特别有用,尤其是对于一次读取整个内容不切实际的大文件。

The readline() method is used to read one line from a file at a time. This method is useful when you need to process a file line by line, especially for large files where reading the entire content at once is not practical.

Syntax

以下是 Python 中 readline() 方法的基本语法 −

Following is the basic syntax of the readline() method in Python −

file_object.readline(size)

其中,

Where,

  1. file_object is the file object returned by the open() function.

  2. size is an optional parameter specifying the maximum number of bytes to read from the line. If omitted or set to a negative value, the method reads until the end of the line.

Example

在以下示例中,以只读模式打开文件“example.txt”。然后使用 readline() 方法读取文件的第 1 行 −

In the example below, we are opening the file "example.txt" in read mode. We then use the readline() method to read the first line of the file −

# Open the file in read mode
file = open('example.txt', 'r')

# Read the first line of the file
line = file.readline()

# Print the line
print(line)

# Close the file
file.close()

以下是上面代码的输出: -

Following is the output of the above code −

welcome to Tutorialspoint.

Reading a File Using readlines() Method

readlines() 方法读取文件中的所有行,并作为字符串列表返回。列表中的每个字符串都代表文件中的单行,包括每行末尾的换行符。

The readlines() method reads all the lines from a file and returns them as a list of strings. Each string in the list represents a single line from the file, including the newline character at the end of each line.

当需要一次处理或分析文件的所有行时,此方法特别有用。

This method is particularly useful when you need to process or analyse all lines of a file at once.

Syntax

以下是 Python 中 readlines() 方法的基本语法 −

Following is the basic syntax of the readlines() method in Python −

file_object.readlines(hint)

其中,

Where,

  1. file_object is the file object returned by the open() function.

  2. hint is an optional parameter that specifies the number of bytes to read. If specified, it reads lines up to the specified bytes, not necessarily reading the entire file.

Example

在此示例中,以只读模式打开文件“example.txt”。然后使用 readlines() 方法读取文件中的所有行,并作为字符串列表返回 −

In this example, we are opening the file "example.txt" in read mode. We then use the readlines() method to read all the lines from the file and return them as a list of strings −

# Open the file in read mode
file = open('example.txt', 'r')

# Read all lines from the file
lines = file.readlines()

# Print the lines
for line in lines:
   print(line, end='')

# Close the file
file.close()

以上代码的输出如下所示 −

Output of the above code is as shown below −

welcome to Tutorialspoint.
Hi Surya.
How are you?.

Using "with" Statement

Python 中的 “with” 语句用于异常处理。处理文件时,使用 “with” 语句可确保文件在读取后正确关闭,即使出现异常也是如此。

The "with" statement in Python is used for exception handling. When dealing with files, using the "with" statement ensures that the file is properly closed after reading, even if an exception occurs.

Example

以下是一个使用 with 语句打开、读取和打印文件内容的简单示例 −

Following is a simple example of using the with statement to open, read, and print the contents of a file −

# Using the with statement to open a file
with open('example.txt', 'r') as file:
   content = file.read()
   print(content)

我们得到了如下输出 −

We get the output as follows −

welcome to Tutorialspoint.
Hi Surya.
How are you?.

Reading a File in Binary Mode

默认情况下,对文件对象执行的读/写操作在文本字符串数据上进行。如果我们要处理不同类型文件,例如媒体文件 (mp3)、可执行文件 (exe) 或图片 (jpg),则必须通过在读/写模式中添加 'b' 前缀以二进制模式打开文件。

By default, read/write operation on a file object are performed on text string data. If we want to handle files of different types, such as media files (mp3), executables (exe), or pictures (jpg), we must open the file in binary mode by adding the 'b' prefix to the read/write mode.

Writing to a Binary File

假设 test.bin 文件已以二进制模式写入 −

Assuming that the test.bin file has already been written in binary mode −

# Open the file in binary write mode
with open('test.bin', 'wb') as f:
   data = b"Hello World"
   f.write(data)

Example

要读取二进制文件,我们需要以 'rb' 模式打开它。然后对 read() 方法的返回值进行解码,然后再进行打印 −

To read a binary file, we need to open it in 'rb' mode. The returned value of the read() method is then decoded before printing −

# Open the file in binary read mode
with open('test.bin', 'rb') as f:
   data = f.read()
   print(data.decode(encoding='utf-8'))

它将生成如下输出:

It will produce the following output −

Hello World

Reading Integer Data From a File

要将整数数据写入二进制文件,应使用 to_bytes() 方法将整数对象转换为字节。

To write integer data to a binary file, the integer object should be converted to bytes using the to_bytes() method.

Writing an Integer to a Binary File

以下是如何将整数写入二进制文件的示例 −

Following is an example on how to write an integer to a binary file −

# Convert the integer to bytes and write to a binary file
n = 25
data = n.to_bytes(8, 'big')

with open('test.bin', 'wb') as f:
   f.write(data)

Reading an Integer from a Binary File

要从二进制文件中读回整数数据,请使用 from_bytes() 方法将 read() 函数的输出转换回整数 −

To read back the integer data from the binary file, convert the output of the read() function back to an integer using the from_bytes() method −

# Read the binary data from the file and convert it back to an integer
with open('test.bin', 'rb') as f:
   data = f.read()
   n = int.from_bytes(data, 'big')
   print(n)

Reading Float Data From a File

对于在二进制文件中处理浮点数数据,我们需要使用来自 Python 标准库的 struct 模块。此模块有助于在 Python 值和表示为 Python 字节对象的 C 结构之间进行转换。

For handling floating-point data in binary files, we need to use the struct module from Python’s standard library. This module helps convert between Python values and C structs represented as Python bytes objects.

Writing a Float to a Binary File

要将浮点数数据写入二进制文件,我们将使用 struct.pack() 方法将浮点数转换为字节对象 −

To write floating-point data to a binary file, we use the struct.pack() method to convert the float into a bytes object −

import struct

# Define a floating-point number
x = 23.50

# Pack the float into a binary format
data = struct.pack('f', x)

# Open the file in binary write mode and write the packed data
with open('test.bin', 'wb') as f:
   f.write(data)

Reading Float Numbers from a Binary File

要从二进制文件中读取浮点数数据,我们将使用 struct.unpack() 方法将字节对象转换回浮点数 −

To read floating-point data from a binary file, we use the struct.unpack() method to convert the bytes object back into a float −

import struct

# Open the file in binary read mode
with open('test.bin', 'rb') as f:
   # Read the binary data from the file
   data = f.read()

   # Unpack the binary data to retrieve the float
   x = struct.unpack('f', data)[0]

   # Print the float value
   print(x)

Reading and Writing to a File Using "r+" Mode

当一个文件打开用于读取 (使用 'r' 或 'rb') 时,不可能写入数据,除非关闭文件并以不同模式重新打开。要同时执行读和写操作,我们在模式参数中添加 '' 字符。使用 'w' 或 'r+' 模式时,可以使用 write() 和 read() 方法,而不必关闭文件。

When a file is opened for reading (with 'r' or 'rb'), writing data is not possible unless the file is closed and reopened in a different mode. To perform both read and write operations simultaneously, we add the '' character to the mode parameter. Using 'w' or 'r+' mode enables using both write() and read() methods without closing the file.

File 对象还支持 seek() 函数,它允许将读/写指针重新定位到文件中的任何所需的字节位置。

The File object also supports the seek() function, which allows repositioning the read/write pointer to any desired byte position within the file.

Syntax

以下是 seek() 方法的语法:

Following is the syntax for seek() method −

fileObject.seek(offset[, whence])

Parameters

  1. offset − This is the position of the read/write pointer within the file.

  2. whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file’s end.

Example

以下程序以 'r+' 模式(读写模式)打开一个文件,寻找文件中的某个位置,并从该位置读取数据 −

The following program opens a file in 'r+' mode (read-write mode), seeks a certain position in the file, and reads data from that position −

# Open the file in read-write mode
with open("foo.txt", "r+") as fo:
   # Move the read/write pointer to the 10th byte position
   fo.seek(10, 0)

   # Read 3 bytes from the current position
   data = fo.read(3)

   # Print the read data
   print(data)

执行上面的代码后,我们得到以下输出: -

After executing the above code, we get the following output −

rat

Reading and Writing to a File Simultaneously in Python

当一个文件打开用于写入 (使用 'w' 或 'a') 时,不可能从中读取数据,并且尝试这样做会引发 UnsupportedOperation 错误。

When a file is opened for writing (with 'w' or 'a'), it is not possible to read from it, and attempting to do so will throw an UnsupportedOperation error.

类似地,当一个文件打开用于读取 (使用 'r' 或 'rb') 时,不允许写入数据。要在读和写之间切换,通常需要关闭文件,然后以所需模式重新打开。

Similarly, when a file is opened for reading (with 'r' or 'rb'), writing to it is not allowed. To switch between reading and writing, you would typically need to close the file and reopen it in the desired mode.

要同时执行读和写操作,可以在模式参数中添加 '' 字符。使用 'w' 或 'r+' 模式时,可以使用 write() 和 read() 方法,而不必关闭文件。

To perform both read and write operations simultaneously, you can add the '' character to the mode parameter. Using 'w' or 'r+' mode enables both write() and read() methods without needing to close the file.

此外,File 对象还支持 seek() 函数,它允许将读/写指针重新定位到文件中的任何所需的字节位置。

Additionally, the File object supports the seek() function, which allows you to reposition the read/write pointer to any desired byte position within the file.

Example

在此示例中,我们以 'r+' 模式打开文件并向文件中写入数据。seek(0) 方法将指针重新定位到文件开头 −

In this example, we open the file in 'r+' mode and write data to the file. The seek(0) method repositions the pointer to the beginning of the file −

# Open the file in read-write mode
with open("foo.txt", "r+") as fo:
   # Write data to the file
   fo.write("This is a rat race")

   # Rewind the pointer to the beginning of the file
   fo.seek(0)

   # Read data from the file
   data = fo.read()
   print(data)

Reading a File from Specific Offset

我们可以使用 seek() 方法在指定偏移处设置他文件当前的位置。

We can set the he file’s current position at the specified offset using the seek() method.

  1. If the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write.

  2. If the file is opened only for writing in append mode using 'a', this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+').

  3. If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.

请注意并非所有文件对象都可寻址。

Note that not all file objects are seekable.

Example

以下示例演示了如何使用 seek() 方法对文件执行同时读/写操作。文件以 w+ 模式(读写模式)打开,添加了一些数据,然后在特定位置读取和修改该文件 −

The following example demonstrates how to use the seek() method to perform simultaneous read/write operations on a file. The file is opened in w+ mode (read-write mode), some data is added, and then the file is read and modified at a specific position −

# Open a file in read-write mode
fo = open("foo.txt", "w+")

# Write initial data to the file
fo.write("This is a rat race")

# Seek to a specific position in the file
fo.seek(10, 0)

# Read a few bytes from the current position
data = fo.read(3)
print("Data read from position 10:", data)

# Seek back to the same position
fo.seek(10, 0)

# Overwrite the earlier contents with new text
fo.write("cat")

# Rewind to the beginning of the file
fo.seek(0, 0)

# Read the entire file content
data = fo.read()
print("Updated file content:", data)

# Close the file
fo.close()

以下是上面代码的输出: -

Following is the output of the above code −

Data read from position 10: rat
Updated file content: This is a cat race