Python Files
Read a File:
- It is important to close the file if you open it with open()
- The "r" indicates "read" permission, other permissions will be demonstrated later
- If no file path is specified before the file name, it will look for the file in the directory of your coding file
Safe File Reading (takes care of closing after):
- This is a better way to read a file, so that you don't accidentally leave files open
- This takes care of closing the file even if your program ends due to an exception
Read One Line at a Time:
- This is useful if you want to work with each line as you read it
Write a File:
- The "w" indicates "write"
- If this file exists, it will overwrite what is currently on it. If not, it will create the file.
Append Text to a File:
- This will add text after the text that is already in the file
- The only code difference from writing the file is the "a" instead of "w"
Challenge
Write code that will write a file that stores a list of names, append a name to that file, then read the file and display its contents.