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
withstatements to automatically open and close the file as soon as the program gets out of the
with open('document.txt') as f: # Previously f = open('document.txt') print(f.read()) print('Done!')
askeyword is used to create an alias. In this example, we create an alias
fwhich refers to
Notice that there are no
f.close()calls. That is handled automatically. As soon as the program enters the
with open()block, the file
document.txtis opened and as soon as the program gets out of the body of the
withblock, 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
.close()-ing them every time.
You are asked to multiply two numbers located in the
numbers.txtfile on separate lines.
The output of the program should contain a single integer - the product of the two numbers.