April 2017
Beginner to intermediate
312 pages
7h 23m
English
So far, we discussed different flags that could be used to open files in different modes. The examples we discussed followed a common pattern—open the file, perform read/write operations and close the file. There is an elegant way of interacting with files using the with keyword. If there are any errors during the execution of the code block that interacts with a file, the with keyword ensures that the file is closed and the associated resources are cleaned up on exiting the code block. As always, let's review the with keyword with an example:
if __name__ == "__main__": with open('write_file.txt', 'r+') as file: # read the contents of the file and print to the screen print(file.read()) file.write("This is a line appended ...Read now
Unlock full access