Python中的WITH语句有什么用途?

来自:互联网
时间:2023-08-19
阅读:

Python中的WITH语句有什么用途?

在本文中,我们将学习有关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循环遍历给定文本文件的每一行。

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

Example

的中文翻译为:

示例

# 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块

Example

的中文翻译为:

示例

# 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__()
<p>在实现了这些方法之后,您可以在类的对象上使用with语句。</p>
  • 当调用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 模块将一个方法转换为上下文管理器。

Example

的中文翻译为:

示例

# 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

的翻译为:

exampleFile.txt

Hello tutorialsPoint python

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

结论

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

返回顶部
顶部