with statement

In some cases, when writing big programs, we might forget to close the files. Manually opening and closing them seems like a lot of repetitive work. To avoid that issue, we can use with statements to automatically open and close the file as soon as the program gets out of the with block:
with open('document.txt') as f:   # Previously f = open('document.txt')
The as keyword is used to create an alias. In this example, we create an alias f which refers to open('document.txt').
Notice that there are no f.open() calls or f.close() calls. That is handled automatically. As soon as the program enters the with open() block, the file document.txt is opened and as soon as the program gets out of the body of the with block, the file is closed. So, when the program reaches the statement print('Done!') the file has already been closed.
This is the preferred way of working with files over .open() and .close()-ing them every time.


You are asked to multiply two numbers located in the numbers.txt file on separate lines.
The output of the program should contain a single integer - the product of the two numbers.

To check your solution you need to sign in
Sign in to continue