File Handling

Carson West

Python 1 Home

File Handling

Key aspects to remember about file handling in Python:

file = open("my_file.txt", "r") #Opens file for reading
file = open("my_file.txt", "r")
contents = file.read() #reads entire file
lines = file.readlines() #reads entire file into list of lines
for line in file: #iterates over lines
  print(line)
file.close() #IMPORTANT: Always close the file!
file = open("my_file.txt", "w")
file.write("This is some text.\n")
file.write("This is another line.\n")
file.close()
try:
    file = open("my_file.txt", "r")
    # ... file operations ...
except FileNotFoundError:
    print("File not found!")
finally:
    file.close() #This will still execute even if exception occurs.  Best way to ensure file is closed
with open("my_file.txt", "r") as file:
    contents = file.read()
    # ... process contents ...

# File is automatically closed here.

File IO Modes, Handling Binary Files