Python Files

Read a File:

myFile = open("/myPath/myFile.txt","r") print(myFile.read()) myFile.close()

- 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):

with open ("/myPath/myFile.txt","r") as myFile: print(myFile.read())

- 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:

with open ("/myPath/myFile.txt","r") as myFile: for myLine in myFile: print(myLine)

- This is useful if you want to work with each line as you read it

Write a File:

with open ("/myPath/myFile.txt","w") as myFile: myFile.write("This text")

- 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:

with open ("/myPath/myFile.txt","a") as myFile: myFile.write("Text to add")

- 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.

Completed