Python 中的 WITH 语句有什么用?

pythonprogrammingserver side programming

在本文中,我们将了解 Python 中的"with"语句及其用法。

  • Python 中的 with 语句用简单的简写代替了 try-catch 块。

  • 更重要的是,它确保在处理后立即关闭资源。

  • 读取或写入文件是 with 语句的常见用途。

  • 上下文管理器是支持 with 语句的函数或类。上下文管理器使您能够在需要时打开和关闭资源。

  • 例如,open() 函数就是上下文管理器。当您使用 with 语句调用 open() 函数时,文件会在您处理完后自动关闭。

使用"with"语句打开和读取文件

算法(步骤)

以下是执行所需任务需要遵循的算法/步骤 -

  • 使用 open() 函数(打开文件并返回文件对象作为结果)通过传递文件名和模式作为参数以只读模式打开文本文件(此处"r"代表只读模式)。

with open(inputFile, 'r') as fileData:
  • 使用 readlines() 函数获取给定文本文件的行列表。

file.readlines(hint)
  • 使用 for 循环遍历给定文本文件的每一行。

  • 打印文本文件的相应行。

示例

# input file path inputFile = "ExampleTextFile.txt" print("The lines of a given Text File are:") # Opening the given file in read-only mode. with open(inputFile, 'r') as fileData: # Read the above file lines using readlines() fileLines = fileData.readlines() # Traverse in the each line of the text file for textLine in fileLines: # printing each line print(textLine)

输出

The lines of a given Text File are:
Good Morning this is Tutorials Point sample File
Consisting of Specific
Good source codes in Python,Seaborn,Scala
Summary and Explanation

With 关键字不仅用于以读取模式打开文件,还可以为打开的文件分配别名。

使用"with"语句替换 try-catch 块

在 Python 中,您可以使用 try-catch 错误处理来打开和写入文件。

在底层,with 语句替换了以下类型的 try-catch 块

示例

# opening the file in write mode using the open() function inputFile = open("tutorialsFile.txt", "w") # handling the exceptions using try-catch blocks try: # writing text into the file inputFile.write("Hello tutorialsPoint python") finally: # closing the file inputFile.close()

输出

Hello tutorialsPoint python

此程序打开文件 tutorialsFile.txt。如果不存在这样的文件,程序将创建它。然后代码将"Hello tutorialsPoint python"写入文件,然后关闭它。

这种方法没有任何问题。但是,有一种更优雅的方法可以使用 with 语句来实现这一点。

现在让我们使用 with 语句重新创建前面的示例 -

# opening a file in write mode with an alias name using with statement with open("tutorialsFile.txt", "w") as file: # writing text into the file file.write("Hello tutorialsPoint python")

这简化了代码,因为 with 语句可以在使用文件后处理关闭文件。这就是为什么一般来说,使用 with 语句是在 Python 中打开文件的首选技术。

Python"with"语句和上下文管理器

处理文件时,您可能认为 with 语句仅适用于 open() 函数。但事实并非如此。还可以创建支持 with 语句的类和对象。

上下文管理器是支持 with 语句的类或函数

如果您想在项目中增加资源管理,可以使用上下文管理器。要被视为上下文管理器,类必须实现以下两种方法 -

  • __enter__()
  • __exit__()

实现这些方法后,可以在类的对象上使用 with 语句。

  • 调用 with 语句时,会调用 __enter__() 方法。

  • 退出 with 块的范围时,会调用 __exit__()。

创建文件写入器上下文管理器

此类的功能与 open() 方法相同

class FileWriter(object): def __init__(self, fileName): self.fileName = fileName def __enter__(self): self.file = open(self.fileName, "w") return self.file def __exit__(self, exception_type, exception_value, traceback): self.file.close()

上述程序的用法

  • 使用 FileWriter(filename),创建一个新的 FileWriter 对象并调用 __enter__ ()。

  • __enter__() 方法用于初始化所需的资源。它在此场景中打开一个文本文件。它还必须返回资源的描述符,因此它返回打开的文件。

  • as file 将文件分配给变量文件。

  • 最后,将使用获取的资源执行的代码放在冒号后的 with 块中。

  • 当此代码完成执行时,会自动调用 __exit__() 方法。在这种情况下,它会关闭文件。

如何编写上下文管理器方法?

之前编写的上下文管理器是一个类,但是如果您想创建一个与 open() 函数相当的上下文管理器方法,该怎么办?Python 还允许您编写上下文管理器方法。

使用 contextlib 模块将方法转换为上下文管理器。

示例

# importig the contextmanager from contextlib module from contextlib import contextmanager # Marking the file_open() function as a context manager # using contextmanager decorator @contextmanager def file_open(name): try: file = open(name, "w") yield file finally: file.close() with file_open("exampleFile.txt") as file: file.write("Hello tutorialsPoint python")

exampleFile.txt

Hello tutorialsPoint python

在这里,我们创建了一个新函数,并用 with 关键字命名。当我们调用该函数时,它会尝试以写入模式打开指定的文件并返回结果。如果发生错误,则文件将被关闭。

结论

我们在本文中学习了如何使用 with 语句和示例。


相关文章