Python basics-elegant with as statement

When you have finished using a resource, you need to manually close it, such as operating files and establishing a database connection. However, in the process of using resources, if an exception is encountered, it is likely that the error is directly thrown, resulting in too late to close the resource.

try:
    file = open("test.txt", "a+")
    file.write("hello,python\n")
finally:
    file.close()

Python provides the with statement syntax to build the process of creating and releasing resources. With is a new keyword and always accompanied by the context manager. The function is the same as the "try-finally" above, and the code is more concise

with open("test.txt", "a+") as file:
    file.write("hello,with as")

The with statement is followed by the open () method. If it has a return value, you can use the as' statement to assign it to the file. "as" is another keyword that refers to the return value of the open function. When the with statement block exits, the close () method is automatically called. Even if an exception occurs in write (), it can ensure that the close () method is called.

#with...as...语句结束时,自动调用f.close()
#a表示:在文件末尾追加
def write_txt_file(path, txt):  # 写文件
    with open(path, 'a', encoding='gbk') as f:
        return f.write(txt)
#每次运行程序前,需要删除上一次的文件
#默认字符编码为GBK
def read_txt_file(path):
    with open(path, 'r', encoding='gbk') as f:
        return f.read()
Published 395 original articles · won 130 · 200,000 views +

Guess you like

Origin blog.csdn.net/qq_40507857/article/details/93602140