在Python中使用带有示例的关键字

带有关键字的Python

with是python中的一个关键字(区分大小写),它类似于的“ using”语句VB.net或/和C#.net。它创建一个with块,执行该with块,该使用块使用with关键字声明的变量。

基本上,with关键字用于确保__exit__方法在块的末尾被调用。就像尝试...最终阻止。

它实现并遵循上下文管理器的方法,其中调用__enter__和__exit__方法。

例如,如果您正在使用文件,则可以创建带有关键字的变量/对象以打开文件,with块可能包含文件操作。并且在执行该块之后,无论块是否存在错误,文件都将关闭。

with关键字的语法

    with expression [as variable]:
	    with-block-statement(s)

示例

    # 有声明有声明打开文件并创建with块
    with open(file_name, "w") as myfile:
        myfile.write("Welcome @ nhooo!")

with关键字的Python示例

示例1:打开一个文件并使用with关键字编写文本。

# 有声明有声明python代码演示示例 
# 有声明有声明与关键字

# 有声明有声明打开文件并使用 
# 有声明"with statement"

# 有声明file name
file_name = "file1.txt"

# 有声明有声明打开文件并创建with块
with open(file_name, "w") as myfile:
    myfile.write("Welcome @ nhooo!")

# 有声明ensure that file is closed or not
if myfile.closed:    
    print("file is closed")

输出结果

file is closed

文件的内容:

Welcome @ nhooo!