bzal bzal - 6 months ago 8
Python Question

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

When so many examples are non-self explanatory and the documentation not too helpful, Beginning Python I came across with statement used in a code as such:

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


after spending some hour on the internet I found something that gave me a quite understandable explanation that the with statement was meant to use multiple statements, but then again what that meant, I was not so sure of. After spending hours again, I found that the
open(fn, 'r')
code was meant to read the file with the given filename
(with other operations of 'w', etc.)
, but the following lines as the
f.readlines()
, are hard to find. Therefore, I have no idea what the above code does. My questions are therefore enlisted as:


  1. What does the code exactly do?

    What exactly is the with statement and how's it using multiple
    statement?

    What is the as in the code for?

    What does the f.readline() implement in the code?

    Why is the comparison:



if int(value) == vl:
cn += 1

even made?

Answer

I commented to try explain;

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

It is counting the number of times some number appears in a file, but very hard to say though because its exact behavior depends on the arguments supplied at run time!

EDIT: As a follow up, I recommend reading the link @PascalvKooten posted in the comments, very clear explanation of exactly what the with statement is

Comments