how to use with open

with open('output.txt', 'w') as file:  # Use file to refer to the file object
  file.write('Hi there!')
# more down here

Here is what the above code is Doing:
1. The first line opens the file in write mode.
2. The second line writes the string ‘Hi there!’ to the file.
3. The third line closes the file.

You can open a file in read mode (‘r’) or write mode (‘w’) or append mode (‘a’), or you can do all three at once using ‘r+’.

If you want to read a file’s contents, you can use the read() method. This will return the entire contents of the file as a single string.

If you want to read a file line by line, you can iterate over the file object. This is memory efficient, fast, and leads to simple code: