File I/O Basics
File Input/Output (I/O) is a fundamental operation in Python programming that allows developers to read from and write to files. Understanding file handling is crucial for tasks like data processing, logging, and configuration management.
Basic File Opening Methods
Python provides several methods to open files:
## Open file in read mode
file = open('example.txt', 'r')
## Open file in write mode
file = open('example.txt', 'w')
## Open file in append mode
file = open('example.txt', 'a')
File Opening Modes
Mode |
Description |
Purpose |
'r' |
Read mode |
Default mode, opens file for reading |
'w' |
Write mode |
Creates new file or truncates existing file |
'a' |
Append mode |
Adds new content to the end of the file |
'r+' |
Read and write mode |
Opens file for both reading and writing |
Safe File Handling with Context Managers
The recommended way to handle files is using context managers:
## Recommended approach
with open('example.txt', 'r') as file:
content = file.read()
## File is automatically closed after this block
File Reading Methods
## Read entire file
with open('example.txt', 'r') as file:
full_content = file.read()
## Read line by line
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
## Read specific number of characters
with open('example.txt', 'r') as file:
partial_content = file.read(50)
File Writing Methods
## Write to a file
with open('output.txt', 'w') as file:
file.write('Hello, LabEx!')
## Write multiple lines
lines = ['First line', 'Second line', 'Third line']
with open('output.txt', 'w') as file:
file.writelines(lines)
File Handling Best Practices
flowchart TD
A[Open File] --> B{Choose Correct Mode}
B --> |Read| C[Use 'r' mode]
B --> |Write| D[Use 'w' mode]
B --> |Append| E[Use 'a' mode]
A --> F[Always Use Context Manager]
A --> G[Close File After Use]
Common File Operations Workflow
- Open the file with appropriate mode
- Perform required operations (read/write)
- Close the file (automatically done with context managers)
- Handle potential exceptions
By mastering these file I/O basics, you'll be well-prepared to handle file operations efficiently in your Python projects, whether you're working on data analysis, configuration management, or logging systems.