Important Notes: File Handling in Python (Class XII)
Introduction to Files
Python files are used to permanently store input data and outputs. File storage allows reusability and
persistence beyond program execution.
Types of Files
- Text File: Human-readable, uses characters, EOL as \n.
- Binary File: Non-human-readable, stores actual content (images, audio, etc.) as byte stream.
Opening and Closing a Text File
- Use open(filename, mode) to open a file.
- Common modes: 'r' (read), 'w' (write), 'a' (append), '+r' (read/write), 'b' (binary).
- Always close a file using [Link]().
- Use 'with open() as' for automatic closure.
Writing to a Text File
- write(): Writes a string.
- writelines(): Writes list of strings.
- Use '\n' to insert new lines.
Reading from a Text File
Important Notes: File Handling in Python (Class XII)
- read(n): Reads n characters.
- readline(): Reads one line.
- readlines(): Returns all lines as a list.
Setting Offsets in a File
- tell(): Returns current byte position.
- seek(offset, ref): Moves file pointer. ref = 0 (start), 1 (current), 2 (end).
Creating and Traversing a Text File
- Use loops with readline() or read() to read contents.
- Use write() or writelines() to write contents.
Pickle Module
- Used to serialize (dump) and deserialize (load) Python objects to/from binary files.
- dump(obj, file): Writes object.
- load(file): Reads object.