"with"


#1

Your following code can have a problem, if for example .write() has errors, or .close() is forgotten:

my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w")
for item in my_list:
    f.write(str(item) + "\n")
f.close()

Here is the new code using with - no need to .close() the file, it is done automatically, even if I/O goes wrong! :smile:

my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10
with open("output.txt", "w") as f:
    for item in my_list:
        f.write(str(item) + "\n")