12. Working with Files and I/O
Level: IntermediateDuration: 26m
What Is File I/O?
File I/O (Input/Output) lets your Python programs interact with files. You can store data permanently, read configuration files, save logs, and more.
Opening a File
Python uses the built-in open() function to work with files.
python
file = open("example.txt", "r") # r = read mode
content = file.read()
print(content)
file.close() # Always close files💡 Always close files after opening them to free system resources. Better yet, use a `with` statement.
File Modes
| Mode | Description |
|---|---|
| r | Read (default). File must exist. |
| w | Write. Overwrites file or creates new. |
| a | Append. Adds to end of file. |
| x | Exclusive create. Errors if file exists. |
| r+ | Read and write. |
Using with for Safe File Handling
The with statement automatically closes the file after you're done.
python
with open("example.txt", "r") as file:
content = file.read()
print(content)Reading from Files
python
# Read entire file
with open("example.txt", "r") as file:
print(file.read())
# Read one line
with open("example.txt", "r") as file:
print(file.readline())
# Read all lines as list
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)Writing to Files
python
# Overwrite file
with open("notes.txt", "w") as file:
file.write("Hello from Python!\n")
# Append to file
with open("notes.txt", "a") as file:
file.write("This is a new line.\n")Reading and Writing Together
python
with open("data.txt", "w+") as file:
file.write("Python file handling!\n")
file.seek(0) # Return to beginning
print(file.read())Handling File Errors
Use try/except to avoid program crashes if a file is missing.
python
try:
with open("missing.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found. Check the filename.")Mini Project Step
Modify your calculator program to save a history of operations to a text file named `history.txt`. Each time a calculation is performed, write it to the file.