Class XII Computer Science
Quick Notes on Chapter: File Handling in Python
1. Introduction to Files
● Files allow data to be stored permanently on secondary storage devices.
● File types: Text files (human-readable) and Binary files (non-human-readable).
2. Types of Files
● Text Files: Contain plain text, stored as ASCII or UNICODE values. Common
extensions: .txt, .csv, .py.
● Binary Files: Contain non-text data like images, audio, video. Require specific software
to read/write.
3. File Operations
● Opening a File: Use open(filename, mode) to get a file object. Modes include:
○ 'r': Read
○ 'w': Write (overwrites if exists)
○ 'a': Append
○ 'b': Binary mode
○ +: Read/Write
● Closing a File: Use file_object.close() to free system resources.
4. Writing to Files
● write(): Writes a single string to a file.
● writelines(): Writes a sequence of strings (like a list or tuple) to a file.
5. Reading from Files
● read(n): Reads n bytes (or the entire file if n is not provided).
● readline(n): Reads one line or up to n bytes of a line.
● readlines(): Reads all lines and returns a list of strings.
6. File Pointers
● tell(): Returns the current position of the file pointer in bytes.
● seek(offset, from_what): Moves the file pointer to a specified location.
○ from_what values: 0 (start), 1 (current position), 2 (end).
7. Using with Clause
● Automatically closes the file after operations:
python
with open("file.txt", "r") as f:
content = f.read()
8. The Pickle Module
● Used for serialization (converting Python objects to byte streams) and deserialization.
● pickle.dump(): Writes serialized data to a binary file.
● pickle.load(): Reads serialized data from a binary file.
9. Common Programs
Creating the file:
with open("file.txt", "w") as f:
f.write("Hello, World!")
Reading a file:
with open("file.txt", "r") as f:
print(f.read())
Using Pickle
import pickle
with open("data.pkl", "wb") as f:
pickle.dump([1, 2, 3], f)
10. Key Differences
● Text vs Binary Files: Text is human-readable; Binary is not.
● readline() vs readlines(): readline() reads one line, while readlines()
returns all lines as a list.
● write() vs writelines(): write() adds one string; writelines() accepts an
iterable of strings.
11. Good Practices
● Always close files or use with to ensure files are closed automatically.
● For binary data, use appropriate modes like 'wb' or 'rb'.