Python 中文件访问模式有哪些区别?

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

Python 的文件处理能力对于各种应用至关重要。理解不同的文件访问模式对于有效地管理和操作文件至关重要。这个实验(Lab)将深入研究 Python 中常见的文件访问模式、它们的区别,以及如何为你的特定用例选择合适的模式。

在这个实验(Lab)中,你将学习 Python 中基本的文件访问模式,探索它们的常见用例,并了解如何为你的文件操作选择合适的模式。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("Catching Exceptions") python/FileHandlingGroup -.-> python/file_opening_closing("Opening and Closing Files") python/FileHandlingGroup -.-> python/file_reading_writing("Reading and Writing Files") python/FileHandlingGroup -.-> python/file_operations("File Operations") subgraph Lab Skills python/catching_exceptions -.-> lab-397713{{"Python 中文件访问模式有哪些区别?"}} python/file_opening_closing -.-> lab-397713{{"Python 中文件访问模式有哪些区别?"}} python/file_reading_writing -.-> lab-397713{{"Python 中文件访问模式有哪些区别?"}} python/file_operations -.-> lab-397713{{"Python 中文件访问模式有哪些区别?"}} end

理解和实践读取模式('r'

在 Python 中,文件访问模式指定了文件应该如何打开以及允许哪些操作(如读取或写入)。理解这些模式对于有效的文件处理至关重要。当使用内置的 open() 函数时,你需要提供文件路径,还可以选择性地提供一个模式字符串。例如,open('my_file.txt', 'r') 以读取模式打开文件。

以下是常见模式的快速概览:

  • 读取模式('r':以读取方式打开(默认)。指针位于文件开头。如果文件不存在,则引发 FileNotFoundError 异常。
  • 写入模式('w':以写入方式打开。如果文件存在,则截断(清空)文件;如果文件不存在,则创建文件。指针位于文件开头。
  • 追加模式('a':以写入方式打开。如果文件存在,则指针位于文件末尾;如果文件不存在,则创建文件。新数据添加到文件末尾。
  • 读取和写入('r+':以读取和写入方式打开一个已存在的文件。指针位于文件开头。
  • 写入和读取('w+':以写入和读取方式打开。截断或创建文件。指针位于文件开头。
  • 追加和读取('a+':以追加和读取方式打开。写入时指针位于文件末尾。如果文件不存在,则创建文件。

让我们从最基本的模式开始练习:读取('r')。此模式专门用于读取现有文件的内容。文件指针从文件开头开始。请记住,尝试以 'r' 模式打开一个不存在的文件会导致错误。

首先,我们需要一个文件来读取。使用 LabEx 中的 VS Code 编辑器,在文件资源管理器中导航到 /home/labex/project 目录。创建一个名为 my_reading_file.txt 的新文件。将以下行添加到该文件并保存:

This is the first line.
This is the second line.

现在,在同一目录下创建一个名为 read_example.py 的 Python 脚本。添加以下代码,该代码以读取模式打开文本文件,读取其内容并打印出来。我们包含一个 try...except 块,以优雅地处理可能找不到文件的情况。

try:
    ## Open the file in read mode ('r')
    with open('/home/labex/project/my_reading_file.txt', 'r') as file:
        ## Read the entire content of the file
        content = file.read()
        print("File content:")
        print(content)
except FileNotFoundError:
    print("Error: The file my_reading_file.txt was not found.")
except Exception as e:
    print(f"An error occurred: {e}")

print("\\nFinished reading the file.")

保存此 Python 脚本。接下来,打开 VS Code 中的终端(Terminal > New Terminal)。通过运行 pwd 确保你在正确的目录中,它应该显示 /home/labex/project

使用 Python 解释器运行脚本:

python read_example.py

你应该在终端中看到 my_reading_file.txt 的内容,后跟完成消息:

File content:
This is the first line.
This is the second line.

Finished reading the file.

这演示了使用 'r' 模式成功打开和读取文件。

Illustration of reading a file

实践写入模式('w'

当你想要写入文件时,可以使用写入模式('w')。请注意:如果文件已经存在,以 'w' 模式打开它将会截断(truncate)它,这意味着它之前的所有内容都将被删除。如果文件不存在,'w' 模式将为你创建它。此模式非常适合创建新文件或从现有文件重新开始。

让我们尝试写入一个文件。在你的 /home/labex/project 目录中,创建一个名为 write_example.py 的新 Python 文件。添加以下代码。此脚本将以写入模式打开(或创建)my_writing_file.txt,并将两行内容写入其中。

try:
    ## Open the file in write mode ('w')
    ## If the file exists, its content will be overwritten.
    ## If the file does not exist, it will be created.
    with open('/home/labex/project/my_writing_file.txt', 'w') as file:
        ## Write some content to the file
        file.write("This is the first line written in write mode.\n")
        file.write("This is the second line.\n")
    print("Content successfully written to my_writing_file.txt")

except Exception as e:
    print(f"An error occurred: {e}")

print("\nFinished writing to the file.")

保存 write_example.py 脚本。在终端(仍在 /home/labex/project 中)运行该脚本:

python write_example.py

你应该看到一条确认消息:

Content successfully written to my_writing_file.txt

Finished writing to the file.

为了确认文件已创建并且包含正确的文本,请在终端中使用 cat 命令:

cat /home/labex/project/my_writing_file.txt

输出应该与脚本写入的内容完全一致:

This is the first line written in write mode.
This is the second line.

这演示了如何使用 'w' 模式创建或覆盖文件,并将内容写入其中。

实践追加模式('a'

与写入模式('w')不同,追加模式('a')用于将内容添加到现有文件的末尾,而不会删除其当前内容。如果文件不存在,'a' 模式将创建它。打开文件时,文件指针会自动定位到文件末尾,因此任何 write() 操作都将追加数据。

让我们将一些行追加到我们在上一步中创建的 my_writing_file.txt。在 /home/labex/project 中创建一个名为 append_example.py 的新 Python 脚本,其中包含以下代码:

try:
    ## Open the file in append mode ('a')
    ## If the file exists, new content will be added to the end.
    ## If the file does not exist, it will be created.
    with open('/home/labex/project/my_writing_file.txt', 'a') as file:
        ## Append some content to the file
        file.write("This line is appended.\n")
        file.write("Another line is appended.\n")
    print("Content successfully appended to my_writing_file.txt")

except Exception as e:
    print(f"An error occurred: {e}")

print("\nFinished appending to the file.")

保存此脚本。现在,从终端执行它:

python append_example.py

该脚本将确认追加操作:

Content successfully appended to my_writing_file.txt

Finished appending to the file.

要查看结果,请再次使用 cat 查看整个文件:

cat /home/labex/project/my_writing_file.txt

你应该看到原来的两行,后跟两个新追加的行:

This is the first line written in write mode.
This is the second line.
This line is appended.
Another line is appended.

追加模式对于诸如添加日志条目或向数据文件添加新记录而不丢失先前数据之类的任务非常有用。

实践读/写模式并选择正确的模式

Python 还提供了允许在同一 open() 上下文中同时进行读取和写入的模式。这些模式提供了更大的灵活性,但需要仔细处理文件指针。

  • 读和写('r+':打开一个现有文件以进行读取和写入。指针从头开始。写入将从指针位置覆盖现有内容。
  • 写和读('w+':打开一个文件以进行写入和读取。如果文件存在,则截断该文件;如果文件不存在,则创建该文件。指针从头开始。
  • 追加和读('a+':打开一个文件以进行追加(在末尾写入)和读取。如果文件不存在,则创建该文件。指针从末尾开始写入,但你可以移动它(例如,使用 file.seek(0))以从头开始读取。

让我们演示 'r+'。我们将使用在步骤 1 中创建的 my_reading_file.txt。我们将打开它,读取内容,然后将指针移回开头并覆盖文件的开头。

/home/labex/project 中创建一个名为 rplus_example.py 的 Python 文件。添加以下代码:

try:
    ## Open the file in read and write mode ('r+')
    ## The file must exist for this mode.
    with open('/home/labex/project/my_reading_file.txt', 'r+') as file:
        ## Read the initial content
        initial_content = file.read()
        print("Initial file content:")
        print(initial_content)

        ## Move the file pointer back to the beginning
        print("\nMoving pointer to the beginning using file.seek(0).")
        file.seek(0)

        ## Write new content at the beginning (overwriting existing content)
        print("Writing new content...")
        file.write("Prepended line 1.\n")
        file.write("Prepended line 2.\n")

        ## If the new content is shorter than what was overwritten,
        ## the rest of the original content might remain unless truncated.
        ## We can use file.truncate() after writing to remove any trailing old data.
        print("Truncating file to the current position to remove old trailing data.")
        file.truncate()

        print("\nContent written and file truncated.")

except FileNotFoundError:
    print("Error: The file was not found. 'r+' requires the file to exist.")
except Exception as e:
    print(f"An error occurred: {e}")

print("\nFinished with r+ mode example.")

此脚本以 'r+' 模式打开文件,读取,寻址回到开头(file.seek(0)),写入新行(覆盖),然后使用 file.truncate() 删除可能存在于新写入文本之外的任何剩余原始内容。

保存 rplus_example.py。在运行它之前,让我们确保 my_reading_file.txt 具有其原始内容:

echo "This is the first line." > /home/labex/project/my_reading_file.txt
echo "This is the second line." >> /home/labex/project/my_reading_file.txt

现在,从终端运行 Python 脚本:

python rplus_example.py

你将看到打印的初始内容,后跟有关该过程的消息:

Initial file content:
This is the first line.
This is the second line.


Moving pointer to the beginning using file.seek(0).
Writing new content...
Truncating file to the current position to remove old trailing data.

Content written and file truncated.

Finished with r+ mode example.

使用 cat 检查最终文件内容:

cat /home/labex/project/my_reading_file.txt

由于覆盖和截断,输出应仅显示新写入的内容:

Prepended line 1.
Prepended line 2.

选择适当的文件访问模式

选择正确的模式至关重要。这是一个快速指南:

  • 使用 'r' 对现有文件进行只读访问。
  • 使用 'w' 创建新文件完全替换现有文件的内容。
  • 使用 'a' 添加到文件末尾,而不会丢失现有数据(适用于日志)。
  • 使用 'r+' 从头开始**读取和修改***现有*文件。
  • 使用 'w+' 创建或覆盖文件,然后读取/写入它。
  • 使用 'a+' 追加到文件,并且能够读取它(需要寻址)。

下表总结了关键行为:

模式 读取 写入 如果不存在则创建 如果存在则截断 指针位置(初始)
'r' 开始
'w' 开始
'a' 结尾
'r+' 开始
'w+' 开始
'a+' 结尾

通过考虑是否需要读取、写入、追加、处理现有文件或创建新文件,你可以自信地为你的任务选择最合适的模式。

总结

在这个实验中,你学习了 Python 中各种文件访问模式及其主要区别。你分别探索了用于基本读取、写入和追加操作的 'r''w''a' 模式。你还简要地了解了读写模式('r+''w+''a+'),这些模式提供了更大的灵活性。

通过实践这些模式并了解它们在文件创建、截断和指针位置方面的行为,你现在有能力为你在 Python 中的文件处理任务选择合适的模式。这些知识是有效管理和操作应用程序中的文件的基础。