带有 'with' 语句的代码有什么作用?

what does the codes with the 'with' statement do?

当这么多示例无法自我解释且文档帮助不大时,开始 Python 我遇到了 with 代码中使用的语句:

def r_f(fn, n, vl):
    cn, rd = 0, 0
    with open(fn, 'r') as f:
        for value in f.readlines():
            rd += 1
            if rd > n:
                break
            if int(value) == vl:
                cn += 1

    return cn  

在互联网上花了几个小时后,我发现了一些可以理解的解释,即 with 语句是为了使用多个语句,但话又说回来,我不太确定那是什么意思。又花了几个小时后,我发现 open(fn, 'r') 代码是用来读取给定文件名 (with other operations of 'w', etc.) 的文件的,但是下面的 f.readlines() 行很难找到。因此,我不知道上面的代码做了什么。因此,我的问题被列为:

  1. 这段代码到底做了什么?

    with 语句到底是什么以及它如何使用多个语句 陈述?

    代码中的 as 是做什么用的?

    f.readline() 在代码中实现了什么?

    为什么是比较:

如果 int(值) == vl: cn += 1

甚至做了?

我发表评论试图解释一下;

#this is your standard method definition
def r_f(fn, n, vl):
        #these are local variables
        cn, rd = 0, 0
        #we are saying;
        #in the scope of this with statement, the variable f
        #is equal to the file object returned by open
        with open(fn, 'r') as f:
            #for every line in the file
            #(because readlines returns a list of all the lines)
            for value in f.readlines():
                #increment this variable by 1
                rd += 1
                #if rd is greater than n
                if rd > n:
                    #break out of this loop
                    break
                #if the integer representation of the line we read
                #is equal to v1
                if int(value) == vl:
                    #then increase this variable by 1
                    cn += 1
        #we return this value to the function that called us
        return cn  

What does the code exactly do?

它正在计算某个数字在文件中出现的次数,但很难说,因为它的确切行为取决于 运行 时提供的参数!

编辑:作为后续,我建议阅读评论中发布的 link @PascalvKooten,非常清楚地解释 with 语句是什么

在开始阅读其他人编写的源代码之前,您必须先阅读文档。

检查 this official documentation 是否有 with 个语句。

您复制的函数执行以下操作: 它有三个参数。然后它将 cnrd 变量设置为 0。 with open(fn, 'r') as f 表示以阅读模式打开名为 fn 的文件,并从现在起将其命名为 f。然后你有 for 循环读取你当前打开文件的每一行,f 并对每一行做一些事情。首先它递增 rd,如果 rd 大于 n 则循环中断,否则如果值(通过 int() 函数将 value 转换为整数)等于vl,然后它递增 cn 和 returns 它。