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循环遍历给定文本文件的每一行。
-
打印文本文件的相应行。
示例
# 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将文件分配给变量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")
示例文件.txt
Hello tutorialsPoint python
这里,我们创建了一个新的函数,并用with关键字命名。当我们调用该函数时,它尝试以写模式打开指定的文件并返回结果。如果发生错误,文件将被关闭。
结论
我们在本文中学习了如何使用with语句和示例。