Understand how to work with files using I/O operations in Python.
File handling in Python allows you to create, read, update, and delete files directly from your Python code. It is crucial when working with external data, logs, or reports.
'r' β Read (default): Opens file for reading, error if file doesnβt exist.'w' β Write: Creates a new file or truncates existing one.'a' β Append: Opens file for appending data to end.'x' β Create: Creates file, fails if file already exists.'b' β Binary mode (e.g., 'rb' or 'wb')'t' β Text mode (default)file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
file = open("example.txt", "w")
file.write("Hello, this is a test.")
file.close()
file = open("example.txt", "a")
file.write("\nAdding a second line.")
file.close()
with for Auto-closewith open("example.txt", "r") as file:
print(file.read())
This is the recommended way as it automatically closes the file.
File Handling Assignmentswith context managertry...exceptos.path.exists()