Chapter 2: File Handling in Python - Class XII
2.1 Introduction to Files
- Files store data permanently on secondary storage.
- Used to avoid repetitive input and reuse output.
2.2 Types of Files
- Text File: Human-readable, .txt, .py, etc.
- Binary File: Non-human-readable, e.g., images, videos.
2.3 Opening and Closing a Text File
- open(filename, mode)
- File Modes:
r : Read (start)
w : Write (start, overwrites)
a : Append (end)
r+ : Read/Write (start)
a+ : Append/Read (end)
Add b for binary: rb, wb, etc.
- close(): to close the file
- with open(...) as f: Automatically closes file
2.4 Writing to a Text File
- write(): writes a string
- writelines(): writes a list of strings
- Convert numbers to strings using str()
- flush(): clears buffer to file
2.5 Reading from a Text File
- read(n): reads n characters
- readline(n): reads one line (max n characters)
- readlines(): reads all lines as list
- split(): split into words
- splitlines(): split into lines
2.6 Setting Offsets in a File
- tell(): get current byte position
- seek(offset, from): move file pointer
0: start, 1: current, 2: end
2.7 Creating and Traversing a Text File
- Write: open in "w"/"a", use input loop
- Read: open in "r", use readline() in loop
2.8 The pickle Module
- Pickling: Serialize Python object to binary
- Unpickling: Deserialize from binary to object
- dump(obj, file): write to binary file
- load(file): read from binary file
Example:
import pickle
data = [1, 'Name', 20]
with open("data.dat", "wb") as f:
pickle.dump(data, f)
Summary
- Text files: ASCII characters, human-readable
- Binary files: byte streams, not human-readable
- Use proper file modes and close files after use
- Pickle module handles object serialization