when dealing with file input and output it is important to always close files files that remain opene when program finishes unexpectedly due to programming errorcan cause considerable system problems for this reason it is recommended to open files via context management the syntax is as follows with open('output txt '' 'as ff write ('hi there !'context management ensures that file is correctly closed even when the program is terminated prematurely an example is given in the next programwhich outputs the mostfrequent words in dicken' tale of two citieswhich can be downloaded from the book' github site as ataleof cities txt note that in the next programthe file ataleof cities txt must be placed in the current working directory the current working directory can be determined via import os followed by cwd os getcwd(numline dict {with open('ataleof cities txt 'encoding ="utf "as finfor line in finwords line split (for in words if not in dictdict[ elsedict[ += numline + sd sorted (dict ,key=dict get reverse =true#sort the dictionary print (number of unique words {}\nformat (len(dict))print ("ten most frequent words :\ "print ("{: {}format ("word"count ")print ( '-'for in range ( , )print ("{: {}format (sd[ ]dict[sd[ ]])number of unique words ten most frequent words word count the and of to in his was that