File I/O (Input/Output) allows programs to interact with external files on disk, like saving data to a text file or loading configurations. Python makes this straightforward using the built-in open() function. Always use the context manager (with statement) to automatically close files and handle resources safely.
Key Concepts
Reading FilesTips and Best Practices
- Opening a File: file = open('filename.txt', 'mode')
- Modes control access: read-only, write, etc.
- Reading: Pull data from the file into memory (as strings or lists).
- Writing: Push data from memory to the file.
- Closing: Frees resources; with handles this automatically.
- Error Handling: Use try-except for issues like "file not found."
- Binary Files: For images/PDFs, add 'b' to mode (e.g., 'rb').
Mode | Description | Use Case | Overwrites? |
|---|---|---|---|
'r' | Read (default) | Load existing file | No |
'w' | Write | Create/overwrite text file | Yes |
'a' | Append | Add to end of file | No |
'r+' | Read + Write | Modify existing file | No |
'rb'/'wb' | Binary Read/Write | Images, executables | Varies |
- Read Entire File:python
with open('example.txt', 'r') as file: content = file.read() # Returns full string print(content) - Read Line by Line:python
with open('example.txt', 'r') as file: line = file.readline() # First line as string # Or loop: for line in file: # Iterates over lines print(line.strip()) # strip() removes \n - Read All Lines into List:python
with open('example.txt', 'r') as file: lines = file.readlines() # List of strings print(lines[0]) # First line
- Write String:python
with open('output.txt', 'w') as file: file.write("Hello, World!\n") # \n for new line - Append Text:python
with open('output.txt', 'a') as file: file.write("More text!\n") - Write List of Lines:python
lines = ["Line 1\n", "Line 2\n"] with open('output.txt', 'w') as file: file.writelines(lines)
python
# Read from input.txt
with open('input.txt', 'r') as infile:
data = infile.read().upper() # Convert to uppercase
# Write processed to output.txt
with open('output.txt', 'w') as outfile:
outfile.write(data)
print("File processed!")- Encoding: For non-ASCII text, add encoding='utf-8' to open().
- Exceptions: python
try: with open('missing.txt', 'r') as file: print(file.read()) except FileNotFoundError: print("File not found!") - CSV/JSON: Use csv or json modules for structured data (e.g., import csv; csv.reader()).
- Performance: For large files, read in chunks: file.read(1024) (bytes at a time).