Up until now, all the data we’ve used disappears as soon as the program stops. File I/O allows you to save data permanently to a file on your hard drive or read data that already exists.
1. The open() Function
To work with a file, you must first open it. The open() function takes two main arguments:
File Path: The name/location of the file.
Mode: ModeName Description
r'ReadDefault. Opens for reading; error if file doesn't exist.'w'WriteOpens for writing; overwrites existing content.'a'AppendOpens for writing; adds to the end of existing content.'x'CreateCreates the file; error if it already exists.
2. The with Statement (Best Practice)
In C, you have to remember to fclose() your files. In Python, we use the with keyword. This is called a Context Manager. It automatically closes the file for you, even if an error occurs.