File IO Modes

Carson West

File Handling

File IO Modes

Python’s built-in open() function allows for various file access modes, influencing how the file is handled during operations. These modes are specified as a second argument to open().

Common Modes:

Example Usage:

# Reading a file
f = open("my_file.txt", "r")
contents = f.read()
f.close()

# Writing to a file
f = open("my_file.txt", "w")
f.write("Hello, world!")
f.close()

# Appending to a file
f = open("my_file.txt", "a")
f.write("\nThis is appended text.")
f.close()

#Binary read
f = open("image.jpg","rb")
image_data = f.read()
f.close()

# safer way to handle files: using 'with' statement. Auto closes file for you.
with open("my_file.txt", "r") as file:
    contents = file.read()
    print(contents)

File Handling Best Practices Error Handling with Files Context Managers