1# Reference https://docs.python.org/3/library/functions.html#open
2
3# Method 1
4file = open("welcome.txt", "r") # mode can be r(read) w(write) and others
5data = file.read()
6file.close()
7
8# Method 2 - automatic close
9with open("welcome.txt") as infile:
10 data = file.read()
11
1>>> with open('workfile') as f:
2... read_data = f.read()
3
4>>> # We can check that the file has been automatically closed.
5>>> f.closed
6True
7
1with open('output.txt', 'w') as file: # Use file to refer to the file object
2
3 file.write('Hi there!')